HttpURLConnection发送POST请求传递JSON参数

java 复制代码
public class POSTJson2 {
    public static void main(String[] args) {
        try {

            String defURL = "https://api.apiopen.top/api/login";
            URL url = new URL(defURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");//请求POST方式
            con.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出,默认值为 false
            
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            String body = "{\"account\":\"309324904@qq.com\",\"password\":\"123456\"}";
            writer.write(body);
            writer.flush();
            writer.close();

            int code = con.getResponseCode();
            System.out.println("http状态码:" + code);
            if (code == HttpURLConnection.HTTP_OK) {
                System.out.println("测试成功");
            } else {
                System.out.println("测试失败:" + code);
            }

            // 获取服务端响应,通过输入流来读取URL的响应
            InputStream is = con.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();

            // 关闭连接
            con.disconnect();

            // 打印读到的响应结果
            System.out.println("运行结束:" + sbf.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行结果:

http状态码:200
测试成功
运行结束:{"code":200,"message":"成功!","result":{"id":572,"createdAt":"2022-12-09 08:28:14","updatedAt":"2022-12-09 08:28:14","deletedAt":null,"account":"309324904@qq.com","level":0,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjU3MiwiaWQiOjU3MiwiY3JlYXRlZEF0IjoiMjAyMi0xMi0wOSAwODoyODoxNCIsInVwZGF0ZWRBdCI6IjIwMjItMTItMDkgMDg6Mjg6MTQiLCJkZWxldGVkQXQiOm51bGwsImFjY291bnQiOiIzMDkzMjQ5MDRAcXEuY29tIiwibGV2ZWwiOjAsImV4cCI6MTcyMDk2MDU2NCwiaXNzIjoiYXBpX29wZW4iLCJuYmYiOjE3MjAzNTQ3NjR9.NaW12ztp0jy3auF3ZACc_OX6vI_ERe87uB6PWC4Ycn8"}}

返回的json数据整理下:

{
    "code": 200,
    "message": "成功!",
    "result": {
        "id": 572,
        "createdAt": "2022-12-09 08:28:14",
        "updatedAt": "2022-12-09 08:28:14",
        "deletedAt": null,
        "account": "309324904@qq.com",
        "level": 0,
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjU3MiwiaWQiOjU3MiwiY3JlYXRlZEF0IjoiMjAyMi0xMi0wOSAwODoyODoxNCIsInVwZGF0ZWRBdCI6IjIwMjItMTItMDkgMDg6Mjg6MTQiLCJkZWxldGVkQXQiOm51bGwsImFjY291bnQiOiIzMDkzMjQ5MDRAcXEuY29tIiwibGV2ZWwiOjAsImV4cCI6MTcyMDk2MDU2NCwiaXNzIjoiYXBpX29wZW4iLCJuYmYiOjE3MjAzNTQ3NjR9.NaW12ztp0jy3auF3ZACc_OX6vI_ERe87uB6PWC4Ycn8"
    }
}

上面是手写的json字符串,如果使用java官方的安装包javax.json,json字符串拼接如下:

java 复制代码
JsonObject object= Json.createObjectBuilder()
        .add("account","309324904@qq.com")
        .add("password","123456")
        .build();
writer.write(object.toString());

完整代码如下:

java 复制代码
import javax.json.Json;
import javax.json.JsonObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class POSTJson2 {
    public static void main(String[] args) {
        try {
            String defURL = "https://api.apiopen.top/api/login";
            URL url = new URL(defURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");//请求POST方式
            con.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出,默认值为 false

            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            JsonObject object= Json.createObjectBuilder()
                    .add("account","309324904@qq.com")
                    .add("password","123456")
                    .build();
            writer.write(object.toString());
            writer.flush();
            writer.close();



            int code = con.getResponseCode();
            System.out.println("http状态码:" + code);
            if (code == HttpURLConnection.HTTP_OK) {
                System.out.println("测试成功");
            } else {
                System.out.println("测试失败:" + code);
            }

            // 获取服务端响应,通过输入流来读取URL的响应
            InputStream is = con.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();

            // 关闭连接
            con.disconnect();

            // 打印读到的响应结果
            System.out.println("运行结束:" + sbf.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
相关推荐
ZhongruiRao16 小时前
Springboot+PostgreSQL+MybatisPlus存储JSON或List、数组(Array)数据
spring boot·postgresql·json
华农第一蒟蒻16 小时前
Java中JWT(JSON Web Token)的运用
java·前端·spring boot·json·token
胡耀超17 小时前
知识图谱入门——8: KG开发常见数据格式:OWL、RDF、XML、GraphML、JSON、CSV。
xml·json·知识图谱·csv·owl·graphml·gml
x-cmd21 小时前
[241005] 14 款最佳免费开源图像处理库 | PostgreSQL 17 正式发布
数据库·图像处理·sql·安全·postgresql·开源·json
先知demons1 天前
js将对象的键和值分别归纳进对象,并将多层对象转化成数据的方法
javascript·vue.js·json
Midsummer啦啦啦1 天前
Python字符串转JSON格式指南
开发语言·python·json
前端 贾公子2 天前
Express内置的中间件(express.json和express.urlencoded)格式的请求体数据
中间件·json·express
迷失蒲公英2 天前
在线JSON可视化工具--支持缩放
json·在线json可视化·在线json格式化
bug菌¹4 天前
滚雪球学MySQL[8.3讲]:数据库中的JSON与全文检索详解:从数据存储到全文索引的高效使用
数据库·mysql·json·全文索引
GDAL5 天前
Efficiently Convert Shapefiles to Protocol Buffers and JSON with Shp2pb
json