HttpClient之post方法和HttpUrlConnection之Get方法

转载自:http://blog.sina.com.cn/s/blog_87216a0001014sm7.html

1. 使用HttpClient:(post方法)

NameValuePair nameValuePair1 = new BasicNameValuePair(“name”, “yang”);
NameValuePair nameValuePair2 = new BasicNameValuePair(“pwd”,”123123”);
List nameValuePairs = new ArrayList();
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);
String validateURL = “http://10.0.2.2:8080/testhttp1/TestServlet“;
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,5000); //设置连接超时为5秒
HttpClient client = new DefaultHttpClient(httpParams); // 生成一个http客户端发送请求对象
HttpPost httpPost = new HttpPost(urlString); //设定请求方式
if (nameValuePairs!=null && nameValuePairs.size()!=0) {
//把键值对进行编码操作并放入HttpEntity对象中
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
}
HttpResponse httpResponse = client.execute(httpPost); // 发送请求并等待响应
// 判断网络连接是否成功
if (httpResponse.getStatusLine().getStatusCode() != 200) {
System.out.println(“网络错误异常!!!!”);
return false;
}
HttpEntity entity = httpResponse.getEntity(); // 获取响应里面的内容
inputStream = entity.getContent(); // 得到服务气端发回的响应的内容(都在一个流里面)
// 得到服务气端发回的响应的内容(都在一个字符串里面)
// String strResult = EntityUtils.toString(entity);
} catch (Exception e) {
System.out.println(“这是异常!”);
}

2. 使用HttpURLConnection:(Get方法)

String validateURL=”http://10.0.2.2:8080/testhttp1/TestServlet?name=yang&pwd=123123”;
try {
URL url = new URL(validateUrl); //创建URL对象
//返回一个URLConnection对象,它表示到URL所引用的远程对象的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); //设置连接超时为5秒
conn.setRequestMethod(“GET”); //设定请求方式
conn.connect(); //建立到远程对象的实际连接
//返回打开连接读取的输入流
DataInputStream dis = new DataInputStream(conn.getInputStream());
//判断是否正常响应数据
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println(“网络错误异常!!!!”);
return false;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(“这是异常!”);
} finally {
if (conn != null) {
conn.disconnect(); //中断连接
}
}
HttpURLconnection的post方法:http://www.cnblogs.com/yaozhenfa/p/3410550.html
http://blog.csdn.net/a9529lty/article/details/6454145

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值