Java 发送post请求

@羲凡——只为了更好的活着

Java 发送post请求

pom依赖
<dependency>
   <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
代码
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class PostDemo {
    public static void main(String[] args) {
        String url = "http://XXXXX:XXXX/test";
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("cur_date", "2020-04-27");
        sendPostWithJson(url,jsonParam.toJSONString());
    }

    public static String sendPostWithJson(String url, String jsonStr) {
        String jsonResult = "";
        try {
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(3000); // //设置连接超时
            client.getHttpConnectionManager().getParams().setSoTimeout(180000); // //设置读取数据超时
            client.getParams().setContentCharset("UTF-8");
            PostMethod postMethod = new PostMethod(url);
            postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            // 非空
            if (null != jsonStr && !"".equals(jsonStr)) {
                StringRequestEntity requestEntity = new StringRequestEntity(jsonStr, "application/json", "UTF-8");
                postMethod.setRequestEntity(requestEntity);
            }
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                jsonResult = postMethod.getResponseBodyAsString();
            } else {
                throw new RuntimeException("接口连接失败!");
            }
            if(postMethod != null){
                postMethod.releaseConnection();
            }
        } catch (Exception e) {
            throw new RuntimeException("接口连接失败!");
        }
        return jsonResult;
    }
}

====================================================================

@羲凡——只为了更好的活着

若对博客中有任何问题,欢迎留言交流

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值