使用httpclient实现post的表单模式请求
先建立两个request与response两个基类,用于存放请求与响应
import java.util.List; public class HttpRequestParams { private String url; private List<BasicPostPara> params; public HttpRequestParams(String url, List<BasicPostPara> params) { super(); this.url = url; this.params = params; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public List<BasicPostPara> getParams() { return params; } public void setParams(List<BasicPostPara> params) { this.params = params; } @Override public String toString() { return "HttpRequestParams [url=" + url + ", params=" + params.toString() + "]"; } }
public class HttpResponse { private int statusCode; private String body; public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String toString() { return "HttpResponse [statusCode=" + statusCode + ", body=" + body + "]"; } }
其中request中的BasicPostPara用来存放post请求对应的参数
public class BasicPostPara { private String key; private String value; public BasicPostPara(String key, String value) { super(); if (key == null) { throw new IllegalArgumentException("Name may not be null"); } this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } @Override public String toString() { if (this.value == null) { return this.key; } return key + "=" + value; } }
然后再编写http请求方法
public HttpResponse postPara(HttpRequestParams req) { HttpResponse res = new HttpResponse(); try { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000); HttpPost post = new HttpPost(req.getUrl()); for (String key : GlobalConfig.HEAD_FINAL_MAP.keySet()) { post.setHeader(key, GlobalConfig.HEAD_FINAL_MAP.get(key)); } List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); for (BasicPostPara postValue : req.getParams()) { pairList.add(new BasicNameValuePair(postValue.getKey(), postValue.getValue())); } post.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); org.apache.http.HttpResponse httpResponse = httpClient.execute(post); int statusCode = httpResponse.getStatusLine().getStatusCode(); if(HttpStatus.SC_OK != statusCode) { throw new HttpException(statusCode); } else { res.setStatusCode(statusCode); res.setBody(EntityUtils.toString(httpResponse.getEntity())); } } catch (Exception e) { e.printStackTrace(); } return res; }
post.setHeader();可以设置头部,因为我的请求头部固定,所以通过static块写好了。
public static final Map<String,String> HEAD_FINAL_MAP ; static { HEAD_FINAL_MAP = new HashMap<String, String>(); HEAD_FINAL_MAP.put("Content-Type", "application/json"); HEAD_FINAL_MAP.put("Accept", "application/json"); }