您的位置:首页 > 理论基础 > 计算机网络

通过httpClient发送json格式数据请求

2015-06-16 09:55 926 查看
//引入maven

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpclient</artifactId>

<version>4.0.1</version>

</dependency>

//重写HTTP请求类

import java.net.URI;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {

public final static String METHOD_NAME = "GET";

public HttpGetWithEntity() {

super();

}

public HttpGetWithEntity(final URI uri) {

super();

setURI(uri);

}

/**

* @throws IllegalArgumentException

* if the uri is invalid.

*/

public HttpGetWithEntity(final String uri) {

super();

setURI(URI.create(uri));

}

@Override

public String getMethod() {

// TODO Auto-generated method stub

return METHOD_NAME;

}

}

//测试调用

/**

* 发送带json格式数据!get請求方式

*

* @param url

* @param jsonParams {\"from\":\"20150101\","to":"20150111"}

* @return

* @throws ServiceException

*/

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, 60000);

httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

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 (UnsupportedEncodingException e) {

throw new ServiceException(HttpExceptionEnums.UNKNOWN_CHARSET_EXCPTION);

} catch (ClientProtocolException e) {

throw new ServiceException(HttpExceptionEnums.ClientProtocolException_EXCPTION);

} catch (ParseException e) {

throw new ServiceException(HttpExceptionEnums.PARSEException_EXCPTION);

} catch (IOException e) {

throw new ServiceException(HttpExceptionEnums.IOException_EXCPTION);

}

return result;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: