如何用java实现PostMan请求:
java实现:
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.PrintWriter; 6 import java.net.HttpURLConnection; 7 import java.net.URL; 8 import java.nio.charset.Charset; 9 import java.nio.charset.StandardCharsets; 10 11 12 /** 13 * @param ediKey 固定值 后面可变 14 * @param ediVal 固定值 后面可变 15 * @author jizm_wb 16 * 17 */ 18 public class TestPostHttp { 19 20 public static void main(String[] args) { 21 String url= "http://localhost:8080/ediserver/gateway.do"; 22 23 String param ="{\r\n" 24 + " \"datas\": [\r\n" 25 + " {\r\n" 26 + " \"ediKey\": \"businessid\",\r\n" 27 + " \"ediVal\": \"R2022000030\"\r\n" 28 + " }\r\n" 29 + " ],\r\n" 30 + " \"imethod\": \"getEdiMessages\"\r\n" 31 + "}"; 32 33 34 String insureResponsePost = insureResponsePost(url,param); 35 36 System.out.println(insureResponsePost); 37 } 38 39 /** 40 * 接口调用(post请求) 数据处理 41 * 42 * @param url 43 * 请求路径 例如:http://127.0.0.1:8080/test/test 44 * @param param 45 * 请求参数 例如:{ "userName":"Lily", "password":"123456" } 46 * @return 响应数据 例如:{ "resultId":"1" "resultMsg":"操作成功" } 47 */ 48 public static String insureResponsePost(String url, String param) { 49 PrintWriter out = null; 50 InputStream is = null; 51 BufferedReader br = null; 52 String result = ""; 53 HttpURLConnection conn = null; 54 StringBuilder stringBuilder = new StringBuilder(); 55 try { 56 URL realUrl = new URL(url); 57 conn = (HttpURLConnection) realUrl.openConnection(); 58 // 设置通用的请求属性 59 conn.setRequestMethod( "POST"); 60 conn.setConnectTimeout(20000); 61 conn.setReadTimeout(300000); 62 conn.setRequestProperty("Charset", "utf-8"); 63 // 传输数据为json,如果为其他格式可以进行修改 64 conn.setRequestProperty( "Content-Type", "application/json"); 65 conn.setRequestProperty( "Content-Encoding", "utf-8"); 66 // 发送POST请求必须设置如下两行 67 conn.setDoOutput( true); 68 conn.setDoInput( true); 69 conn.setUseCaches( false); 70 // 获取URLConnection对象对应的输出流 71 out = new PrintWriter(conn.getOutputStream()); 72 // 发送请求参数 73 out.print(param); 74 // flush输出流的缓冲 75 out.flush(); 76 is = conn.getInputStream(); 77 BufferedReader bufferedReader = null; 78 if (is != null) { 79 // 此处需要将编码格式设置为UTF_8,解决 InputStream 流读取时的中文乱码问题 80 bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); 81 char[] charBuffer = new char[128]; 82 int bytesRead = -1; 83 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { 84 stringBuilder.append(charBuffer, 0, bytesRead); 85 } 86 } else { 87 stringBuilder.append(""); 88 } 89 90 result = stringBuilder.toString(); 91 } catch (Exception e) { 92 System. out.println( "发送 POST 请求出现异常!" + e); 93 e.printStackTrace(); 94 } 95 // 使用finally块来关闭输出流、输入流 96 finally { 97 try { 98 if (out != null) { 99 out.close(); 100 } 101 if (br != null) { 102 br.close(); 103 } 104 if (conn!= null) { 105 conn.disconnect(); 106 } 107 } catch (IOException ex) { 108 ex.printStackTrace(); 109 } 110 } 111 return result; 112 } 113 114 115 }