httpUtils封装

来源:互联网 发布:游戏王vrains知乎 编辑:程序博客网 时间:2024/05/29 15:10
public static HttpEntity getHttpEntity(int request,
List<NameValuePair> nameValuePairLists, String url)
throws Exception {
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
HttpUriRequest httpUriRequest = null;
HttpResponse httpResponse = null;
HttpEntity httpEntity = null;
switch (request) {
case 0:
StringBuffer buffer = new StringBuffer(url);
if (nameValuePairLists != null && nameValuePairLists.size() > 0) {
buffer.append("?");
for (NameValuePair nameValuePair : nameValuePairLists) {
buffer.append(nameValuePair.getName());
buffer.append("=");
buffer.append(nameValuePair.getValue());
buffer.append("&");
}
buffer.deleteCharAt(buffer.lastIndexOf("&"));
httpUriRequest = new HttpGet(buffer.toString());
}
break;
case 1:
httpUriRequest = new HttpPost(url);
if (nameValuePairLists != null && nameValuePairLists.size() > 0) {
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(
nameValuePairLists, "utf-8");
((HttpPost) httpUriRequest).setEntity(encodedFormEntity);
}
break;


}
httpResponse = httpClient.execute(httpUriRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
httpEntity = httpResponse.getEntity();
}


return httpEntity;


}
0 0
原创粉丝点击