package api.utils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.methods.*; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.List; import java.util.Map; /** * @author van * @date 2022/6/6 11:59 * @version 1.0 * msg: */public class HttpUtil { private static final String UTF8 = "utf-8"; public static String get(String url){ CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(url); String result = null; try { HttpResponse httpResponse = client.execute(get); InputStream inStream = httpResponse.getEntity().getContent(); result = streamToString(inStream,UTF8); inStream.close(); } catch (Exception e) { return null; } return result; } public static String GetWithHeader (String url, List urlParameters, Map header) throws URISyntaxException { URI finalURI = new URIBuilder(url).setParameters(urlParameters).build(); CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(finalURI); for(String key: header.keySet()) { get.setHeader(key, header.get(key)); } String result = null; try { HttpResponse httpResponse = client.execute(get); InputStream inStream = httpResponse.getEntity().getContent(); result = streamToString(inStream, UTF8); inStream.close(); } catch (Exception e) { return null; } return result; } public static String PostWithHeader (String URL, String json, Map header) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(URL); for(String key: header.keySet()) { post.setHeader(key, header.get(key)); } String result = null; try { StringEntity s = new StringEntity(json, UTF8); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(s); HttpResponse httpResponse = client.execute(post); InputStream inStream = httpResponse.getEntity().getContent(); result = streamToString(inStream,UTF8); inStream.close(); } catch (Exception e) { return null; } return result; } public static String Post (String URL, String json) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(URL); String result = null; try { StringEntity s = new StringEntity(json, UTF8); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); s.setContentType("application/json"); post.setEntity(s); HttpResponse httpResponse = client.execute(post); InputStream inStream = httpResponse.getEntity().getContent(); result = streamToString(inStream,UTF8); inStream.close(); } catch (Exception e) { return null; } return result; } public static String streamToString(InputStream in, String encoding){ // 将流转换为字符串 try { StringBuffer sb = new StringBuffer(); byte[] b = new byte[1024]; for (int n; (n = in.read(b)) != -1;) { sb.append(new String(b, 0, n, encoding)); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("提取 requestBody 异常", e); } } /** *
     * 方法体说明:向远程接口发起请求,返回字符串类型结果
     * @param url 接口地址
     * @param requestMethod 请求类型
     * @param params 传递参数
     * @return String 返回结果
     * 
*/ public static String httpRequestToString(String url, String requestMethod, Map params){ //接口返回结果 String methodResult = null; try { String parameters = ""; boolean hasParams = false; //将参数集合拼接成特定格式,如name=zhangsan&age=24 for(String key : params.keySet()){ String value = URLEncoder.encode(params.get(key), "UTF-8"); parameters += key +"="+ value +"&"; hasParams = true; } if(hasParams){ parameters = parameters.substring(0, parameters.length()-1); } //是否为GET方式请求 boolean isGet = "get".equalsIgnoreCase(requestMethod); boolean isPost = "post".equalsIgnoreCase(requestMethod); boolean isPut = "put".equalsIgnoreCase(requestMethod); boolean isDelete = "delete".equalsIgnoreCase(requestMethod); //创建HttpClient连接对象 DefaultHttpClient client = new DefaultHttpClient(); HttpRequestBase method = null; if(isGet){ url += "?" + parameters; method = new HttpGet(url); }else if(isPost){ method = new HttpPost(url); HttpPost postMethod = (HttpPost) method; StringEntity entity = new StringEntity(parameters); postMethod.setEntity(entity); }else if(isPut){ method = new HttpPut(url); HttpPut putMethod = (HttpPut) method; StringEntity entity = new StringEntity(parameters); putMethod.setEntity(entity); }else if(isDelete){ url += "?" + parameters; method = new HttpDelete(url); } method.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000); //设置参数内容类型 method.addHeader("Content-Type","application/x-www-form-urlencoded"); //httpClient本地上下文 HttpClientContext context = null; context = HttpClientContext.create(); //访问接口,返回状态码 HttpResponse response = client.execute(method, context); //返回状态码200,则访问接口成功 if(response.getStatusLine().getStatusCode()==200){ methodResult = EntityUtils.toString(response.getEntity()); } client.close(); }catch (UnsupportedEncodingException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } return methodResult; } }