java通过httpClient发送json格式数据请求(GET方式)
概述
在开发过程中和第三方系统对接时遇到需要使用GET请求传递JSON参数,现整理请求方式如下。
HttpGetWithEntity类
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase { public final static String METHOD_NAME = "GET"; public HttpGetWithEntity() { super(); } public HttpGetWithEntity(final URI uri) { super(); setURI(uri); } public HttpGetWithEntity(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
工具类
/** * get 发送 json 参数 * @param ropPath * @param path * @param sk * @param ak * @param date * @param jsonStr * @return */ public static String GetOpenUrlJsonString(String ropPath, String path, String sk, String ak, String date,String jsonStr) { BufferedReader in = null; String result = null; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "GET " ); stringBuilder.append( "application/json " ); stringBuilder.append( date + " " ); stringBuilder.append( path ); String pathAndUrl = stringBuilder.toString(); String Sig = HMACSHA1Utils.getHmacSHA1( sk, pathAndUrl, "HmacSHA1" ); Base64.Encoder encoder = Base64.getEncoder(); //编码 String Signature = encoder.encodeToString( Sig.getBytes() ); String Authorization = "ROP " + ak + ":" + Signature; try { org.apache.http.client.HttpClient httpclient = new DefaultHttpClient(); HttpGetWithEntity requestEntity = new HttpGetWithEntity(ropPath + path); requestEntity.setHeader("Content-Type", "application/json"); requestEntity.setHeader( "User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)" ); requestEntity.setHeader( "Date", date ); requestEntity.setHeader( "Authorization", Authorization ); if (!StringUtils.isEmpty(jsonStr)) { StringEntity se = new StringEntity(jsonStr); requestEntity.setEntity(se); } HttpResponse response = httpclient.execute(requestEntity); int STATUS_CODE = response.getStatusLine().getStatusCode(); if (STATUS_CODE == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity); return result; } if (entity != null) { entity.consumeContent(); } } else { throw new ServiceException("调用失败"); } httpclient.getConnectionManager().shutdown(); } catch (Exception e) { } return null; }
调用:
String date = getGMTDate(); //3.7 获取资源的url String getUrl = "/res/resources/url"; String jsonStr = "{"resourceId":""+resourceId+""}";
String resultDetail = HttpClientUtils.GetOpenUrlJsonString( xxUrl, getUrl, AccessKeySecret, AccessKey, date,jsonStr );