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

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();
		}
	}
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值