各种形式的JAVA网络请求工具类POST/GET/PUT
package com.utils; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @Slf4j public class HttpRequest { /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { LogUtils.debug("url:" + url); LogUtils.debug("param:" + param); PrintWriter out = null; BufferedReader in = null; StringBuilder sb = new StringBuilder(); try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); CommonMail.sendException("http post", "参数:"+param +"/n"+DealString.getFromException(e), 1); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return sb.toString(); } /** * 向指定URL发送GET方法的请求 * * @param url 发送请求的URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, Mapparam) { StringBuilder sb = new StringBuilder(); BufferedReader in = null; try { String urlNameString = url + "?" + getParam(param); URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; UTF-8"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map > map = connection.getHeaderFields(); // 遍历所有的响应头字段 map.forEach((k,v)->{ log.info("{}--->{}",k,v); }); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { sb.append(line); } } catch (Exception e) { LogUtils.debug("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return sb.toString(); } /** * 向指定URL发送GET方法的请求 application/json * * @param url * @param json * @return */ public static String sendPostWithJson(String url, String json) { String returnValue = "接口调用失败"; CloseableHttpClient httpClient = HttpClients.createDefault(); ResponseHandler responseHandler = new BasicResponseHandler(); try { //第一步:创建HttpClient对象 httpClient = HttpClients.createDefault(); //第二步:创建httpPost对象 HttpPost httpPost = new HttpPost(url); //第三步:给httpPost设置JSON格式的参数 StringEntity requestEntity = new StringEntity(json, "utf-8"); requestEntity.setContentEncoding("UTF-8"); httpPost.setHeader("Content-type", "application/json"); httpPost.setEntity(requestEntity); //第四步:发送HttpPost请求,获取返回值 returnValue = httpClient.execute(httpPost, responseHandler); } catch (Exception e) { e.printStackTrace(); CommonMail.sendException("sendPostWithJson请求失败!", "url=" + url + "\r\njson=" + json + "\r\n" + DealString.getFromException(e), 1); } finally { try { httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //第五步:处理返回值 return returnValue; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是Map的形式,请在key为参数,value为值。 * @return 所代表远程资源的响应结果 * @throws Exception */ public static String sendPost(String url, Map param) throws Exception { PrintWriter out = null; BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); HttpURLConnection httpUrlConn = (HttpURLConnection) conn; // 设置通用的请求属性 httpUrlConn.setRequestProperty("accept", "*/*"); httpUrlConn.setRequestProperty("connection", "Keep-Alive"); httpUrlConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setRequestMethod("POST"); httpUrlConn.setReadTimeout(5000); httpUrlConn.setConnectTimeout(5000); // 获取URLConnection对象对应的输出流 out = new PrintWriter(httpUrlConn.getOutputStream()); // 发送请求参数 out.print(getParam(param)); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(httpUrlConn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { LogUtils.debug("发送 POST 请求出现异常!"+e); e.printStackTrace(); throw new Exception("发送 POST 请求出现异常!",e); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result.toString(); } /** * 向指定 URL 发送PUT方法的请求 * @param url * @param json * @return */ public static String sendPutWithJson(String url, String json) { String returnValue = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); ResponseHandler responseHandler = new BasicResponseHandler(); try { //第一步:创建HttpClient对象 httpClient = HttpClients.createDefault(); //第二步:创建httpPost对象 HttpPut httpPost = new HttpPut(url); //第三步:给httpPost设置JSON格式的参数 StringEntity requestEntity = new StringEntity(json, "utf-8"); requestEntity.setContentEncoding("UTF-8"); httpPost.setHeader("Content-type", "application/json"); httpPost.setEntity(requestEntity); //第四步:发送HttpPost请求,获取返回值 returnValue = httpClient.execute(httpPost, responseHandler); } catch (Exception e) { e.printStackTrace(); CommonMail.sendException("sendPostWithJson请求失败!", "url=" + url + "\r\njson=" + json + "\r\n" + DealString.getFromException(e), 1); } finally { try { httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //第五步:处理返回值 return returnValue; } public static String sendXiMaPost(String url, Map paramMap) { String param = getParam(paramMap); return sendXiMaPost(url, param); } /** * 向指定 URL 发送POST方法的请求 * * @param url 发送请求的 URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendXiMaPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8")); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); //判断返回码 if (conn.getResponseCode() == 401 || conn.getResponseCode() == 400) { // return ""; in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); } else { // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); } String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); CommonMail.sendException("http post", "参数:" + param + "/n" + DealString.getFromException(e), 1); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 构建请求参数 * @param params * @return */ public static String getParam(Map params) { StringBuffer sb = new StringBuffer(); String str = ""; if(params!=null){ for (Map.Entry e : params.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append("&"); } str = sb.substring(0, sb.length() - 1); } return str; } public static String encodeURL(String url){ return url.replace("%", "%25").replace("+", "%2B").replace(" ", "%20").replace("/", "%2F") .replace("?", "%3F").replace("#", "%23").replace("&", "%26").replace("=", "%3D") .replace(":", "%3A"); } public static String sendPostJSON(String url, String param) throws Exception { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .retryOnConnectionFailure(Boolean.FALSE) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(50, TimeUnit.SECONDS) .build(); RequestBody body = RequestBody.create(MediaType.parse("application/json"), param); Request.Builder request = new Request.Builder().post(body).url(url); Response response = client.newCall(request.build()).execute(); InputStream is = response.body().byteStream(); String s = new String(readInputStream(is)); LogUtils.debug(s); return s; } private static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } }