java发送json请求

本文介绍了一个使用 Java 进行 HTTP API 测试的例子,通过构造 JSON 请求体并发送 POST 请求来测试本地 API 接口。该示例涵盖了 HttpClient 的使用、JSON 对象和数组的创建以及异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.apache.http.client.HttpClient;  
import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.StringEntity;
import java.nio.charset.Charset;
public class APITest {
    private static HttpClient httpClient = null;  
    private static HttpPost method = null;
    private static String url = "http://localhost:80/api/do";
    public APITest() {
        httpClient = new DefaultHttpClient();
        method = new HttpPost(url);
    }

    public static void main(String[] args) {
        try {
              JSONObject jsonObjectSend = new JSONObject();
              JSONObject bodyJsonObject = new JSONObject();
              JSONArray jsonArray = new JSONArray();
              httpClient = new DefaultHttpClient();
              method = new HttpPost(url);
              String[] devices = {"123","234"};
              bodyJsonObject.put("message", "test");
              bodyJsonObject.put("devices", devices);
              jsonArray.put(0,bodyJsonObject);
              jsonObjectSend.put("body", jsonArray);
              String sendstr = jsonObjectSend.toString();
              method.addHeader("Content-type","application/json; charset=utf-8");
              method.setEntity(new StringEntity(sendstr, Charset.forName("UTF-8")));
              httpClient.execute(method);
              return;
       } catch (Exception e) {
            System.out.println("error....");
            System.out.println(e.toString());
            System.out.println("--------------------");
            System.out.println(e.getMessage());
            System.out.println("--------------------");
            e.printStackTrace();
            return;
       }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值