概述
在开发过程中和第三方系统对接时遇到需要使用GET请求传递JSON参数,现整理请求方式如下。
重写HttpGetWithEntity类
下面是最关键的代码,通过
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public final static String METHOD_NAME = "GET";
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
public HttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
调用方法
public class test{
public static String processGetWithData(String url, String jsonParams) throws ServiceException {
String result = null;
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
try {
HttpGetWithEntity e = new HttpGetWithEntity(url);
e.setHeader("Content-Type", "application/json");
if (!StringUtils.isEmpty(jsonParams)) {
StringEntity se = new StringEntity(jsonParams);
e.setEntity(se);
}
HttpResponse response = httpclient.execute(e);
int STATUS_CODE = response.getStatusLine().getStatusCode();
if (STATUS_CODE == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
if (entity != null) {
entity.consumeContent();
}
} else {
throw new ServiceException(HttpExceptionEnums.CODE_INTERNAL_EXCPTION);
}
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
throw new ServiceException(HttpExceptionEnums.Exception_EXCPTION);
}
return result;
}
}