HttpClient请求服务器 get post

/*
* HTTPClient请求方式请求get方法
*/
public static String login_GET_HttpClient(String name,String pass,String url){
StringBuffer sb=new StringBuffer(url);
sb.append("?username=");
sb.append(name);
sb.append("&userpass=");
sb.append(pass);

String rs="";

//创建httpClient的get请求对象
HttpGet get=new HttpGet(sb.toString());
//设置请求参数
HttpParams params=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params,5*1000);
HttpConnectionParams.setSoTimeout(params, 5*1000);

HttpClient client=new DefaultHttpClient(params);//得到httpClient对象

try {
HttpResponse resp = client.execute(get);//执行请求,得到结果

if(resp.getStatusLine().getStatusCode()==200){
HttpEntity entity=resp.getEntity();//获得相应结果,为HttpEntity类型
rs=EntityUtils.toString(entity, "utf-8");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}

/*
* httpClient请求方式post请求
*/
public static String login_POST_HttpClient(String name,String pass,String url){
String rs="";
//创建httpClient的post请求对象
HttpPost post=new HttpPost(url);
//设置请求参数
HttpParams params=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5*1000);
HttpConnectionParams.setSoTimeout(params, 5*1000);

//传值,创建list集合,向服务器传递请求参数
List<NameValuePair> pair=new ArrayList<NameValuePair>();
NameValuePair p1=new BasicNameValuePair("username", name);
NameValuePair p2=new BasicNameValuePair("userpass", pass);
pair.add(p1);
pair.add(p2);

try {
HttpEntity entity=new UrlEncodedFormEntity(pair,"utf-8");
post.setEntity(entity);//给post请求对象,设置上传的参数

HttpClient client=new DefaultHttpClient(params);
try {
HttpResponse resp = client.execute(post);//得到相应结果

if(resp.getStatusLine().getStatusCode()==200){
HttpEntity entity2 = resp.getEntity();
rs = EntityUtils.toString(entity2, "utf-8");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return rs;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值