HttpUrlConnection和HttpClient和android-async-http框架的GET和POST請求

我叫阿狸貓發表於2014-12-01

1.HttpUrlConnection

public class NetUtil {
	public static String doGet(String username,String password) {
		try {
			String data = "username=" + username + "&password=" + password;
			URL url = new URL("http://115.192.188.146:9090/Android//servlet/LoginServlet?"+data);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(5000);
			
			if(conn.getResponseCode()==200){
				InputStream is = conn.getInputStream();
				String result = getStringFromInputStream(is);
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String doPost(String username,String password) {
		try {
			// post請求的引數
			String data = "username=" + username + "&password=" + password;
			URL url = new URL("http://115.192.188.146:9090/Android//servlet/LoginServlet");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(5000);
			conn.setDoOutput(true);//預設情況下, 系統不允許向伺服器輸出內容
			
			// 獲得一個輸出流, 用於向伺服器寫資料, 預設情況下, 系統不允許向伺服器輸出內容 所以要設定conn.setDoOutput(true);
			OutputStream os = conn.getOutputStream();
			os.write(data.getBytes());//將請求的資料寫入輸出流裡
			os.flush();
			os.close();
			
			if(conn.getResponseCode()==200){
				InputStream is = conn.getInputStream();
				String result = getStringFromInputStream(is);
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static String getStringFromInputStream(InputStream is) {
		try {
			if(is!=null){
				int len = 0;
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while((len=is.read(buffer))!=-1){
					baos.write(buffer, 0, len);
				}
				String result = baos.toString();
				is.close();
				baos.close();
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}


2.HttpClient

public class NetUtil {
	public static String doHttpClientGet(String username,String password) {
		HttpClient client = null;
		try {
			String data = "username=" + username + "&password=" + password;
			
			client = new DefaultHttpClient();
			HttpGet get = new HttpGet("http://10.0.2.2:9090/Android//servlet/LoginServlet?"+data);
			
			HttpResponse response = client.execute(get);
			if(response.getStatusLine().getStatusCode()==200){
				InputStream is = response.getEntity().getContent();
				return getStringFromInputStream(is);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(client!=null){	//關閉連線
				client.getConnectionManager().shutdown();
			}
		}
		return null;
	}

	public static String doHttpClientPost(String username,String password) {
		HttpClient client = null;
		try {
			client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://10.0.2.2:9090/Android//servlet/LoginServlet");
			//設定請求的引數
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("username", username));
			parameters.add(new BasicNameValuePair("password", password));
			//把post請求的引數包裝了一層
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
			//設定引數
			post.setEntity(entity);
			
			HttpResponse response = client.execute(post);
			if(response.getStatusLine().getStatusCode()==200){
				InputStream is = response.getEntity().getContent();
				return getStringFromInputStream(is);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(client!=null){
				client.getConnectionManager().shutdown();	
			}
		}
		return null;
	}
	
	private static String getStringFromInputStream(InputStream is) {
		try {
			if(is!=null){
				int len = 0;
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while((len=is.read(buffer))!=-1){
					baos.write(buffer, 0, len);
				}
				String result = baos.toString();
				is.close();
				baos.close();
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

3.android-async-http  

public class MainActivity extends Activity {

	private EditText et_username;
	private EditText et_password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}
	
	private void init() {
		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
	}

	public void loginGET(View view){
		String username = et_username.getText().toString();
		String password = et_password.getText().toString();
		
		String data = "username=" + username + "&password=" + password;
		String url = "http://10.0.2.2:9090/Android//servlet/LoginServlet?"+data;
		AsyncHttpClient client = new AsyncHttpClient();
		client.get(url, new MyResponseHandler());//get請求
	}
	
	public void loginPOST(View view){
		String username = et_username.getText().toString();
		String password = et_password.getText().toString();
		
		String url = "http://10.0.2.2:9090/Android//servlet/LoginServlet";
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("username", username);
		params.put("password", password);
		client.post(url, params , new MyResponseHandler());//post請求
	}
	
	private class MyResponseHandler extends AsyncHttpResponseHandler{
		//請求成功時呼叫
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
			//這個回撥方法是在主執行緒執行的,所以在這個方法裡可以直接操作UI元件
			Toast.makeText(getApplicationContext(), "成功:"+statusCode+"  body--->"+new String(responseBody), Toast.LENGTH_SHORT).show();
		}
		//請求失敗時呼叫
		@Override
		public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
			Toast.makeText(getApplicationContext(), "失敗:"+statusCode, Toast.LENGTH_SHORT).show();
		}
	}
}


相關文章