第三方请求工具
package com.odfly.module.costpay.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
public void httpRequest() {
HttpURLConnection httpURLConnection = null;
BufferedReader in = null;
PrintWriter out = null;
// OutputStreamWriter out = null;
JSONObject result = new JSONObject();
String urlAddress = "";//请求url
String param = "";//请求参数
try {
URL url = new URL(urlAddress);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content_Type", "application/json");
httpURLConnection.setRequestProperty("Accept_Charset", "UTF-8");
httpURLConnection.setRequestProperty("contentType", "UTF-8");
//发送POST请求参数
out = new PrintWriter(httpURLConnection.getOutputStream());
// out = new OutputStreamWriter(httpURLConnection.getOutputStream(),"utf-8");
out.write(param);
// out.println(strReqJsonStr);
out.flush();
//读取响应
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuffer content = new StringBuffer();
String tempStr = null;
in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
while ((tempStr = in.readLine()) != null) {
content.append(tempStr);
}
//转换成json对象
com.alibaba.fastjson.JSONObject respJson = JSON.parseObject(content.toString());
String resultCode = respJson.getString("errCode");
System.out.println(resultCode);
} else {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
httpURLConnection.disconnect();
}
}
}
httpUtil第三方请求工具
最新推荐文章于 2025-11-11 16:45:00 发布
本文详细介绍了一款基于Java的第三方HTTP请求工具的实现方法,包括如何使用FastJSON进行数据解析,通过设置URL、请求方法及参数,实现POST请求,并处理响应数据。文章深入探讨了工具类中各部分代码的功能,如设置请求头、发送请求参数、读取响应等关键步骤。
7209

被折叠的 条评论
为什么被折叠?



