java post请求接口_Java接口请求之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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值