package com.example.demo; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; public class HttpRequest { public static void main(String []args) throws IOException, JSONException { //请求url String serverURL = "https://service.test.com/sv-sp/truenate"; URL url = new URL(serverURL); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); //header参数connection.setRequestProperty("键","值"); connection.setRequestProperty("Content-Type", "application/json"); connection.connect(); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8"); //获取当前时间戳 long time = new Date().getTime(); JSONArray jsonArray = new JSONArray(); JSONObject parm1 = new JSONObject(); parm1.put("signame","local"); parm1.put("timestamp",time); parm1.put("value",str); //请求包含数组时时,先将数组参数放入JSONArray jsonArray.put(parm1); //body参数 JSONObject parm2 = new JSONObject(); parm2.put("id","1001"); parm2.put("signals", jsonArray); parm2.put("vinne","V2001"); writer.write(parm2.toString()); writer.flush(); StringBuffer sbf = new StringBuffer(); String strRead = null; // 返回结果-字节输入流转换成字符输入流,控制台输出字符 InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while ((strRead = reader.readLine()) != null) { sbf.append(strRead); sbf.append("\r\n"); } reader.close(); connection.disconnect(); String results = sbf.toString(); System.out.println(results); } }
ps:请求头 Connection,Connection设置为 keep-alive用于说明 客户端这边设置的是,本次HTTP请求之后并不需要关闭TCP连接,这样可以使下次HTTP请求使用相同的TCP通道,节省TCP建立连接的时间