Java中用非JSON方式请求第三方接口(form/data方式)

public static String post(String url, HashMap<String, Object> textMap) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse httpResponse = null;
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000)
            .build();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    ContentType contentType = ContentType.create("multipart/form-data",Charset.forName("UTF-8"));
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

    for (String str : textMap.keySet()) {
        try {
            System.out.println(str+"--->"+textMap.get(str).toString());
            multipartEntityBuilder.addTextBody(str, textMap.get(str).toString(), contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);
    try {
        httpResponse = httpClient.execute(httpPost);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    HttpEntity responseEntity = httpResponse.getEntity();
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String resultStr = null;
    if (statusCode == 200) {
        BufferedReader reader = null;
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(responseEntity.getContent(), "utf-8");
            reader = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            String str = "";
            while ((str = reader.readLine()) != null) {
                buffer.append(str);
            }
            resultStr = buffer.toString();
        } catch (UnsupportedOperationException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    if (httpResponse != null) {
        try {
            httpClient.close();
            httpResponse.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return resultStr;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 中调用第三方接口需要使用 Java 提供的网络请求 API,通常有两种方式: 1. 使用 HttpURLConnection 类发送 HTTP 请求 HttpURLConnection 是 Java 中用于发送 HTTP 请求的类,可以使用此类发送 GET、POST、PUT、DELETE 等请求。具步骤如下: ```java // 创建 URL 对象 URL url = new URL("http://example.com/api"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法 conn.setRequestMethod("GET"); // 设置请求头 conn.setRequestProperty("Content-Type", "application/json"); // 发送请求 conn.connect(); // 获取响应码 int responseCode = conn.getResponseCode(); // 获取响应数据 InputStream inputStream = conn.getInputStream(); // 读取响应数据 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); inputStream.close(); // 关闭连接 conn.disconnect(); // 处理响应数据 System.out.println(response.toString()); ``` 2. 使用 HttpClient 库发送 HTTP 请求 HttpClient 是 Apache 提供的开源 HTTP 客户端库,可以用于发送 HTTP 请求,支持 GET、POST、PUT、DELETE 等请求。具步骤如下: ```java // 创建 HttpClient 对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建 HttpGet 或 HttpPost 对象 HttpGet httpGet = new HttpGet("http://example.com/api"); // 设置请求头 httpGet.setHeader("Content-Type", "application/json"); // 发送请求 CloseableHttpResponse response = httpClient.execute(httpGet); // 获取响应数据 HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); // 关闭响应和连接 response.close(); httpClient.close(); // 处理响应数据 System.out.println(result); ``` 需要注意的是,在调用第三方接口时,需要遵循接口提供方的协议和规范,如授权、请求频率等限制。同时,为了保证数据安全,建议将敏感信息加密传输。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值