案例 httpClient 远程调用接口(接上文)
httpClient作为一个http通信库,可通过Api用户数据传输和接收http消息.一般会用到json的工具类,主要代码如下:
package com.juchaosoft.utils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * httpClient 它是一个HTTP通信库,接口调用 HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息 * * @author wang-xiaoming * @date 2019年7月2日 */ public class HttpClient { /** * 请求参数配置 */ private static RequestConfig requestConfig; /** * 默认字符编码:UTF-8 */ public static final String DEFAULT_ENCODING = "UTF-8"; /** * 日志对象 */ protected static final Logger log = LoggerFactory.getLogger(HttpClient.class); static { // 设置请求和传输超时时间 requestConfig = RequestConfig.custom().setSocketTimeout(3000000).setConnectTimeout(3000000).build(); } /** * get请求 * * @param url * url中含有参数或只有url * @return */ public static CloseableHttpResponse get(String url) { CloseableHttpClient client = HttpClients.createDefault(); try { HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); return client.execute(httpGet); } catch (Exception e) { log.error("get 请求异常,e={}", e); } return null; } /** * get 携带参数请求 * * @param url * @param data * @return */ public static CloseableHttpResponse get(String url, Map<String, String> data) { CloseableHttpClient client = HttpClients.createDefault(); try { // uriBuilder中可set属性 URIBuilder uriBuilder = new URIBuilder(url); if (data != null && !data.isEmpty()) { for (String key : data.keySet()) { uriBuilder.setParameter(key, data.get(key)); } } HttpGet httpGet = new HttpGet(uriBuilder.build()); httpGet.setConfig(requestConfig); return client.execute(httpGet); } catch (Exception e) { log.error("get 携带参数请求异常,e={}", e); } return null; } /** * post 请求 * * @param url * @return */ public static CloseableHttpResponse post(String url) { CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); return client.execute(httpPost); } catch (Exception e) { log.error("post 请求异常,e={}", e); } return null; } /** * post 发送byte数组数据请求 * * @param url * @param data * @return */ public static CloseableHttpResponse post(String url, byte[] data) { CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.setEntity(new ByteArrayEntity(data)); return client.execute(httpPost); } catch (Exception e) { log.error("post 发送byte数组数据请求异常,e={}", e); } return null; } /** * post 携带string参数请求 * * @param url * @param data * @return */ public static CloseableHttpResponse post(String url, String data) { CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); if (data != null && !"".equals(data)) { httpPost.setEntity(new StringEntity(data, DEFAULT_ENCODING)); } return client.execute(httpPost); } catch (Exception e) { log.error("post 携带string参数请求异常,e={}", e); } return null; } /** * post 携带hashmap参数请求 * * @param url * @param data * @return */ public static CloseableHttpResponse post(String url, Map<String, String> data) { CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); if (data != null && !data.isEmpty()) { List<NameValuePair> nvpList = new ArrayList<NameValuePair>(); for (String key : data.keySet()) { nvpList.add(new BasicNameValuePair(key, data.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(nvpList, DEFAULT_ENCODING)); } return client.execute(httpPost); } catch (Exception e) { log.error("post 携带hashmap参数请求异常,e={}", e); } return null; } /** * post 携带流参数请求 * * @param url * @param inputStream * @return */ public static CloseableHttpResponse post(String url, InputStream inputStream) { CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); if (inputStream != null) { InputStreamEntity inputEntry = new InputStreamEntity(inputStream); httpPost.setEntity(inputEntry); } return client.execute(httpPost); } catch (Exception e) { log.error("post 携带流参数请求异常,e={}", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("post 携带流参数请求异常,流关闭异常,e={}", e); } inputStream = null; } } return null; } /** * console:输出到控制台 */ public static void console(CloseableHttpResponse chr) throws ParseException, IOException { if (chr != null && chr.getStatusLine().getStatusCode() == 200) { String json = EntityUtils.toString(chr.getEntity(), DEFAULT_ENCODING); log.debug("请求成功,result={}", json); System.out.println("请求成功,result=" + json); } else { log.debug("请求失败,result=null"); System.out.println("请求失败,result=null"); } } public static void main(String[] args) throws ParseException, IOException { // https://blog.csdn.net/u010325193/article/details/84896420 : SLF4J: No SLF4J providers were found. // 测试:POST请求 String json = "{\"paramA\":\"002019031411315646937618369135\",\"paramB\":\"002019070210565431402376498000\"}"; Map<String, String> data = JacksonUtil.mapFromJson(json, String.class, String.class); CloseableHttpResponse chr = post("https://xxx", data); console(chr); // 测试:GET请求 json = "{\"paramA\":\"002019031411315646937618369135\",\"paramB\":\"1145891143915573248\"}"; data = JacksonUtil.mapFromJson(json, String.class, String.class); chr = get("http://xxx", data); console(chr); // 针对url中含有'?'问号的请求,如果有参数拼接请求参数 json = "{\"paramA\":\"\"}"; data = JacksonUtil.mapFromJson(json, String.class, String.class); String url = "http://xxx"; StringBuffer buffer = new StringBuffer(url); if (url.contains("?")) { data.forEach((key, value) -> { buffer.append("&" + key + "=" + value); }); chr = get(buffer.toString(), data); } console(chr); } }
雨淋淋过的季节