`
lichaobao
  • 浏览: 45557 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Web的get、post请求

    博客分类:
  • java
阅读更多

private HttpClient httpClient;

/**
* Get请求
* @param url
* @param params
* @return
*/
public String get(String url, List<NameValuePair> params) {
String body = null;
try {
// Get请求
HttpGet httpGet = new HttpGet(url);
// 设置参数
String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
// 发送请求
HttpResponse httpreSponse = httpClient.execute(httpget);
// 获取返回数据
HttpEntity entity = httpreSponse .getEntity();
body = EntityUtils.toString(entity);
if (entity != null) {
entity.consumeContent();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return body;
}

/**
* // Post请求
* @param url
* @param params
* @return
*/
public String post(String url, List<NameValuePair> params) {
String body = null;
try {
// Post请求
HttpPost httpPost= new HttpPost(url);
// 设置参数
httpPost.setEntity(new UrlEncodedFormEntity(params));
// 发送请求
HttpResponse httpreSponse = httpClient.execute(httpPost);
// 获取返回数据
HttpEntity entity = httpreSponse .getEntity();
body = EntityUtils.toString(entity);
if (entity != null) {
entity.consumeContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return body;
}

public HttpClient getHttpClient() {
return httpClient;
}

public void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics