Httpclient 发送 get 请求
Httpclient 发送get请求:
1、工具客户端代码:
public NmpResponse doGet(NmpRequest request) throws IOException {
logger.info("------------开始GET请求 nmpHttpClient------------");
String charset="UTF-8";
HttpClient httpClient = new HttpClient();
//设置Http连接超时为15秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
Map<String,String> params = request.getParams();
String paramValue ="";
if (null != params && params.size()>0) {
paramValue=paramValue+"?";
for(Map.Entry<String,String> param : params.entrySet()) {
String key = param.getKey();
String paramEncode = null;
if ("?".equals(paramValue)) {
paramEncode = URLEncoder.encode(params.get(key),"UTF-8");//参数转义
paramValue = paramValue+key+"="+ paramEncode;
} else {
paramEncode = URLEncoder.encode(params.get(key),"UTF-8");
paramValue = paramValue+"&"+key+"="+ paramEncode;
}
}
}
String URL =NMP_ROOT_URL+request.getUrl()+paramValue;
System.out.println("访问接口的全路径转义后:"+URL);
GetMethod getMethod = new GetMethod(URL);
getMethod = setHeaderAuthInfo(getMethod);
NmpResponse response = new NmpResponse();
try {
logger.info("------------开始执行GET请求,url:{}------------",URL);
int statusCode = httpClient.executeMethod(getMethod);
logger.info("------------GET请求结束,code={}------------",statusCode);
if (statusCode != HttpStatus.SC_OK){
logger.error("请求出错code={}:{}" ,statusCode ,getMethod.getStatusLine());
}
Header[] headers = getMethod.getResponseHeaders();
byte[] responseBody = getMethod.getResponseBody();
String s = new String(responseBody, charset);
response.setRespBody(responseBody);
response.setRespHeaders(headers);
response.setResponseStr(s);
logger.info("------------结束GET请求 nmpHttpClient------------");
} catch (IOException e){
logger.error("请求出错IOException:{}" ,e);
throw e;
} finally {
getMethod.releaseConnection();//.释放连接
}
return response;
}
2、服务端接收参数的方法可以这样设置:
@GetMapping(value = {"/query/getData"})
public Object getQueryPartition( @RequestParam("parameter") String parameter) {
String catName = "" ;
String layName = "" ;
String parName = "" ;
Integer version = -1 ;
String productVersion = Constant.ProductVersionLastest ;
if (! "".equals(parameter)){
JSONObject jsonObject = JSONObject.parseObject(parameter);
layerName = jsonObject.getString("layName");
partitionName = jsonObject.getString("parName");
if (StringUtils.isEmpty(layName)){
return new JSONObject();
}
if (StringUtils.isEmpty(parName)){
return new JSONObject();
}
if(jsonObject.containsKey("catName")){
catalogName = jsonObject.getString("catName");
}
if(jsonObject.containsKey("version")){
version = Integer.valueOf(jsonObject.getString("version"));
}
if(jsonObject.containsKey("productVersion")){
productVersion = jsonObject.getString("productVersion");
}
}
//这里处理业务的代码省略
return null;
}
3、双端代码已贴,大家可以试一下,有不明白的地方可以留言。
还没有评论,来说两句吧...