1 背景介绍

最近有一个任务,完成数据获取和解析,需要发送带请求参数的post请求,才能拿到数据。之前没有接触过java发送post请求,但有接触过python的requets库,故写下这篇记录一下发送post请求。

2 基本实现

2.1需要的依赖:

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;

idea会自动识别上面这些类,选择自动导入就好。

2.2 工具类实现

HttpUtils,实现发送:

public class HttpUtils {
 public static String sendPostWithJson(String url, String jsonStr, HashMap<String,String> headers) {
        // 返回的结果
        String jsonResult = "";
        try {
            HttpClient client = new HttpClient();
            // 连接超时
            client.getHttpConnectionManager().getParams().setConnectionTimeout(3*1000);
            // 读取数据超时
            client.getHttpConnectionManager().getParams().setSoTimeout(3*60*1000);
            client.getParams().setContentCharset("UTF-8");
            PostMethod postMethod = new PostMethod(url);

            postMethod.setRequestHeader("content-type", headers.get("content-type"));
           
            // 非空
            if (null != jsonStr && !"".equals(jsonStr)) {
                StringRequestEntity requestEntity = new StringRequestEntity(jsonStr, headers.get("content-type"), "UTF-8");
                postMethod.setRequestEntity(requestEntity);
            }
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                jsonResult = postMethod.getResponseBodyAsString();
            } else {
                throw new RuntimeException("接口连接失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException("接口连接失败!");
        }
        return jsonResult;
    }
    }

测试:

public static void main(String[] args) {

    HashMap<String, String> headers = new HashMap<>(3);
    String requestUrl = "http://localhost:8070/test/rz/server/rzxx/at_VaildToken.do";
    String jsonStr = "{\"name\":\"张三\"}";
    headers.put("content-type", "application/json");
    // 发送post请求
    String resultData = HttpUtils.sendPostWithJson(requestUrl, jsonStr,headers);
    // 并接收返回结果
    System.out.println(resultData);
}

解析使用阿里巴巴的fastJSON,把获取到的字符串变为JSON对象,然后进行遍历取出,最后进行操作,提前数据。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐