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

//引入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;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值