美文网首页
Java接口请求之POST

Java接口请求之POST

作者: Jinwei_ | 来源:发表于2020-07-22 10:03 被阅读0次

1、POST请求实践

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);
    }
}

相关文章

网友评论

      本文标题:Java接口请求之POST

      本文链接:https://www.haomeiwen.com/subject/clczkktx.html