H5W3
当前位置:H5W3 > 其他技术问题 > 正文

java使用HttpClients和restTemplate发送HTTP请求

使用HttpClients

public class HttpRequest {
private final static Log log = LogFactory.getLog(HttpRequest.class);
private static final String GZIP_CONTENT_TYPE = "application/x-gzip";
private static final String DEFUALT_CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8";
public static final String USER_AGENT = "Mozilla/5.0 (Linux; Android 4.4.4;  en-us; Nexus 4 Build/JOP40D) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Mobile Safari/537.36";
public static final int default_socketTimeout = 10000;
private HttpRequest(){}
/**
* 发送HTTP_POST请求  时默认采用UTF-8解码
* 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL  请求的url
* @param params 请求参数
* @return
*/
public static String post(String reqURL, Map<String, String> params){
return post(reqURL, params, false, null, null);
}
/**
* 发送HTTP_GET请求
* @param reqURL 请求的url地址(含参数),默认采用utf-8编码
* @return
*/
public static Map<String, Object>  getJson(String reqURL){
String jsonString = get(reqURL,null,false);
Map<String, Object> retMap = new Gson().fromJson(
jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
return retMap;
}
public static String get(String reqURL){
return get(reqURL,null,false);
}
public static String get(String reqURL, String encoding, Boolean inGZIP) {
long responseLength = 0;//响应长度
String responseContent = null; //响应内容
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(reqURL);
if(inGZIP){
httpGet.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
}
httpGet.setHeader(HTTP.USER_AGENT, USER_AGENT);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(default_socketTimeout).setConnectTimeout(default_socketTimeout).build();
httpGet.setConfig(requestConfig);
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
if(null != entity){
responseLength = entity.getContentLength();
if(inGZIP) {
responseContent = unGZipContent(entity, encoding == null ? "UTF-8" : encoding);
} else {
responseContent = EntityUtils.toString(entity, encoding == null ? "UTF-8" : encoding);
}
close(entity);
}
log.debug("请求地址: " + httpGet.getURI());
log.debug("响应状态: " + response.getStatusLine());
log.debug("响应长度: " + responseLength);
log.debug("响应内容: " + responseContent);
} finally {
response.close();//关闭连接,释放资源
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseContent;
}
public static String post(String reqURL, Map<String, String> params, Boolean gzip, String encodeCharset, String decodeCharset) {
String responseContent = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(reqURL);
if(gzip){
httpPost.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
}
httpPost.setHeader(HTTP.USER_AGENT, USER_AGENT);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
Set<Map.Entry<String, String>>  paramSet = params.entrySet();
if(null != paramSet && paramSet.size() > 0){
for(Map.Entry<String,String> entry : paramSet){
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
log.debug("send params:"+formParams.toString());
try {
// 设置参数
httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(default_socketTimeout).setConnectTimeout(default_socketTimeout).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpPost);
try{
HttpEntity entity = response.getEntity();
if (null != entity) {
String contentType = "";
Header[] headers = httpPost.getHeaders(HTTP.CONTENT_TYPE);
if(headers != null && headers.length>0){
contentType = headers[0].getValue();
}
if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
responseContent = unGZipContent(entity,decodeCharset==null ? "UTF-8" : decodeCharset);
}else{
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
}
close(entity);
}
log.debug("请求地址: " + httpPost.getURI());
log.debug("响应状态: " + response.getStatusLine());
log.debug("响应内容: " + responseContent);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseContent;
}
/**
* 解压
* @param entity
* @param encoding
* @return
* @throws IOException
*/
public static String unGZipContent(HttpEntity entity,String encoding) throws IOException {
String responseContent = "";
GZIPInputStream gis = new GZIPInputStream(entity.getContent());
int count = 0;
byte data[] = new byte[1024];
while ((count = gis.read(data, 0, 1024)) != -1) {
String str = new String(data, 0, count,encoding);
responseContent += str;
}
return responseContent;
}
/**
* 压缩
* @param sendData
* @return
* @throws IOException
*/
public static ByteArrayOutputStream gZipContent(String sendData) throws IOException{
if (StringUtils.isBlank(sendData)) {
return null;
}
ByteArrayOutputStream originalContent = new ByteArrayOutputStream();
originalContent.write(sendData.getBytes("UTF-8"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
originalContent.writeTo(gzipOut);
gzipOut.close();
return baos;
}
public static void close(HttpEntity entity) throws IOException {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
final InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
}
//	public static void main(String[] args) {
////		Map<String,String> map = new HashMap<>(2);
////		map.put("uuid","1");
////        String string = HttpRequest.sendGetRequest("https://www.baidu.com?uuid=1");
//		String s = HttpRequest.get("http://192.168.1.152:7300/mock/5eda1999e6bd620018ede134/dataanalysis/component/list");
//		System.out.println(s);
//	}
}
 

使用restTemplate

        private static RestTemplate restTemplate = new RestTemplate();
//方式一:GET 方式获取 JSON 串数据
// String result = restTemplate.getForObject(url, String.class);
//方式二:GET 方式获取 JSON 数据映射后的 Product 实体对象
//Product product = restTemplate.getForObject(url, Product.class);
//方式三:GET 方式获取包含 Product 实体对象 的响应实体 ResponseEntity 对象,用 getBody() 获取
//ResponseEntity<Product> responseEntity = restTemplate.getForEntity(url, Product.class);
Map<String, Object>  result    = restTemplate.getForObject(url, Map.class);
 

参考

  1. JAVA 利用HttpClient封装get和post请求
  2. 掌握 Spring 之 RestTemplate

本文地址:H5W3 » java使用HttpClients和restTemplate发送HTTP请求

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址