标签:uri end https 系统 请求方式 == over ast style
在开发过程中和第三方系统对接时遇到需要使用GET请求传递JSON参数,现整理请求方式如下。
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; } }
标签:uri end https 系统 请求方式 == over ast style
原文地址:https://www.cnblogs.com/g120/p/14835340.html