100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Java实现向指定URL用POST方法发送Json格式字符串参数请求的工具类

Java实现向指定URL用POST方法发送Json格式字符串参数请求的工具类

时间:2023-08-07 09:08:51

相关推荐

Java实现向指定URL用POST方法发送Json格式字符串参数请求的工具类

场景

SpringBoot项目中通过后台Controller向某服务接口发送POST请求。

实现

在项目pom.xml中添加依赖

<dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>2.2</version><scope>compile</scope></dependency><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.6.0</version></dependency>

在util包下新建HttpRequestUtil.java

public class HttpRequestUtil {/*** 定义全局OkHttpClient对象*/private static final OkHttpClient httpClient = new OkHttpClient();/*** 向指定 URL 发送POST方法的请求** @param url* 发送请求的 URL* @param param* 请求参数,请求参数应该是Json格式字符串的形式。* @return 所代表远程资源的响应结果*/public static String sendPost(String url, String jsonData) {PrintWriter out = null;BufferedReader in = null;String result = "";try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection con = realUrl.openConnection();HttpURLConnection conn = (HttpURLConnection) con;// 设置通用的请求属性conn.setRequestMethod("POST"); // 设置Post请求conn.setConnectTimeout(5 * 1000);conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// conn.setRequestProperty("Content-Type",// "application/x-www-form-urlencoded"); // 设置内容类型conn.setRequestProperty("Content-Type","application/json"); // 设置内容类型// conn.setRequestProperty("Content-Length",// String.valueOf(param.length())); //设置长度// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);// 获取URLConnection对象对应的输出流out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));// 发送请求参数// out.print(param);out.write(jsonData);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}byte[] bresult = result.getBytes();result = new String(bresult, "utf-8");} catch (Exception e) {System.out.println("发送 POST 请求出现异常!" + e);e.printStackTrace();}// 使用finally块来关闭输出流、输入流finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}return result;}}

注意根据请求的enctype进行相应的设置

conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 设置内容类型

或者

conn.setRequestProperty("Content-Type","application/json"); // 设置内容类型

在后台Controller调用时只需要:

String URL="http://IP:7788/PostPrintService/Info";Map map=new HashMap();map.put("TableName","wms_receive_order_details");map.put("PrintID",PrintId);String param= JSON.toJSONString(map);String message = HttpRequestUtil.sendPost(URL, param);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。