Java HttpURLConnection POST 请求外部接口

这段代码展示了如何使用FastJSON构造POST请求的参数,并通过Google Guava的Collectors工具处理数据。它创建了一个HTTP POST请求,设置了请求头,发送JSON数据,并读取返回的响应。该方法对于集成API或者处理需要POST提交JSON数据的场景非常有用。
摘要由CSDN通过智能技术生成
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 请求接口
 * @param httpUrl
 * @param httpArg
 * @return
 * @throws Exception
 */
private static String sendPost(String httpUrl,String httpArg) throws Exception {

    StringBuffer sbf = new StringBuffer();
    // Post请求的url,与get不同的是不需要带参数
    URL url = new URL(httpUrl);
    HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
    // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true
    connection.setDoOutput(true);
    // Read from the connection. Default is true.
    connection.setDoInput(true);
    // 默认是 GET方式
    connection.setRequestMethod("POST");
    // Post 请求不能使用缓存
    connection.setUseCaches(false);
    //设置本次连接是否自动重定向
    connection.setInstanceFollowRedirects(true);
    // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
    // 意思是正文是urlencoded编码过的TEXT参数
    connection.setRequestProperty("Content-Type", "application/json");
    //添加请求头参数
    //connection.setRequestProperty("token",TOKEN);
    // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
    // 要注意的是connection.getOutputStream会隐含的进行connect。
    connection.connect();
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
    out.writeBytes(httpArg);
    //流用完记得关
    out.flush();
    out.close();
    //获取响应
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    String strRead = null;
    while ((strRead = reader.readLine()) != null) {
        sbf.append(strRead);
        sbf.append("\r\n");
    }
    reader.close();
    String result = sbf.toString();
    //结束,记得把连接断了
    connection.disconnect();

    return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WS_926

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值