Java模拟HTTP/POST方式请求接口

Java模拟HTTP/POST方式请求接口:

java模拟http/post方式请求接口方法主体:

public String sendPost(JSONObject json, String url){
    String result = "";
    HttpPost post = new HttpPost(url);
    try{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        post.setHeader("Content-Type","application/json;charset=utf-8");
        post.addHeader("Authorization", "Basic YWRtaW46");
        StringEntity postingString = new StringEntity(json.toString(),"utf-8");
        post.setEntity(postingString);
        HttpResponse response = httpClient.execute(post);

        InputStream in = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        StringBuilder strber= new StringBuilder();
        String line = null;
        while((line = br.readLine())!=null){
   
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HttpURLConnection类来模拟HTTP接口POST请求。具体步骤如下: 1. 创建URL对象,指定要请求接口地址。 2. 调用URL对象的openConnection()方法,获取HttpURLConnection对象。 3. 设置HttpURLConnection对象的请求方法为POST。 4. 设置HttpURLConnection对象的请求头信息,包括Content-Type、User-Agent等。 5. 设置HttpURLConnection对象的输出流,用于向接口发送请求参数。 6. 发送请求参数到接口。 7. 获取HttpURLConnection对象的输入流,读取接口返回的数据。 8. 关闭输入流和输出流,释放资源。 示例代码如下: ``` URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", "Mozilla/5."); conn.setDoOutput(true); String requestBody = "{\"name\":\"张三\",\"age\":18}"; OutputStream os = conn.getOutputStream(); os.write(requestBody.getBytes()); os.flush(); os.close(); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = br.readLine()) != null) { response.append(line); } br.close(); is.close(); conn.disconnect(); System.out.println(response.toString()); ``` 以上代码模拟了一个向接口发送JSON格式请求参数的POST请求,并读取接口返回的数据。需要注意的是,请求头信息和请求参数的格式需要根据接口的要求进行设置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值