Java实现HTTP GET 通过 Body 来发送数据
在开发过程中和第三方系统对接时遇到需要使用GET请求传递JSON参数,现整理请求方式如下。
POM
1 <dependency> 2 <groupId>org.apache.httpcomponents</groupId> 3 <artifactId>httpclient</artifactId> 4 <version>4.5.13</version> 5 </dependency>
重写HttpGetWithEntity类
1 public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase { 2 public final static String METHOD_NAME = "GET"; 3 4 public HttpGetWithEntity() { 5 super(); 6 } 7 8 public HttpGetWithEntity(final URI uri) { 9 super(); 10 setURI(uri); 11 } 12 13 public HttpGetWithEntity(final String uri) { 14 super(); 15 setURI(URI.create(uri)); 16 } 17 18 @Override 19 public String getMethod() { 20 // TODO Auto-generated method stub 21 return METHOD_NAME; 22 } 23 24 }
调用方法
public class test { public static JSONObject processGetWithBody(String url, Map<String, Object> args,String charset) { String defaultCharset = "UTF-8"; JSONObject result = new JSONObject(); HttpGetWithEntity getWithEntity = new HttpGetWithEntity(url); JSONObject params = new JSONObject(); for (Map.Entry<String, Object> entry : args.entrySet()) { params.put(entry.getKey(), entry.getValue()); } HttpEntity httpEntity = new StringEntity(params.toJSONString(), ContentType.APPLICATION_JSON); getWithEntity.setEntity(httpEntity); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(getWithEntity)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity responseEntity = response.getEntity(); result = JSONObject.parseObject(EntityUtils.toString(responseEntity, StringUtils.hasText(charset) ? charset : defaultCharset)); } else { // TODO:请求失败逻辑 } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }