jdk HttpURLConnection类请求http接口工具类

本文介绍了一个使用Java实现的HTTP请求处理工具类,支持POST和GET请求,并具备重试机制。该工具类通过设置请求头、编码格式等参数,能够发送携带自定义内容的数据包,并接收服务器响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class HttpUtil {


// post请求
public static final String HTTP_POST = "POST";


// get请求
public static final String HTTP_GET = "GET";


// utf-8字符编码
public static final String CHARSET_UTF_8 = "UTF-8";


// HTTP内容类型
public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";


// HTTP内容类型
public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded;charset=" + CHARSET_UTF_8;


// 请求超时时间
public static final int SEND_REQUEST_TIME_OUT = 20000;


// 将读超时时间
public static final int READ_TIME_OUT = 20000;


/**

* @param requestType
*            请求类型
* @param urlStr
*            请求地址
* @param body
*            请求发送内容
* @return 返回内容
* @throws Exception 
*/
public static String requestMethod(String requestType, String urlStr, String body) throws Exception {
//long star = System.currentTimeMillis();
boolean isDoInput = false;
if (body != null && body.length() > 0){
isDoInput = true;
}
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
URL url = new URL(urlStr);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
if (isDoInput) {
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(body.length()));
}
httpURLConnection.setDoInput(true);
httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT);
httpURLConnection.setReadTimeout(READ_TIME_OUT);
httpURLConnection.setUseCaches(false);
//httpURLConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");  
httpURLConnection.setRequestProperty("Accept-Charset", CHARSET_UTF_8);
httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_FORM_URL);
httpURLConnection.setRequestMethod(requestType);


httpURLConnection.connect();


if (isDoInput) {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(body);
outputStreamWriter.flush();// 刷新
}
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("http error code is :" + httpURLConnection.getResponseCode());
}


if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, CHARSET_UTF_8);
reader = new BufferedReader(inputStreamReader);

while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
}
//httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {// 关闭流
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inputStreamReader != null) {
inputStreamReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//System.out.println("耗时:"+(System.currentTimeMillis()-star)+"毫秒");
return resultBuffer.toString();
}

/**
* 请求重试机制 二次请求需等待0.5秒
* @param requestType 请求类型
* @param action 请求接口
* @param params 请求参数 json格式
* @param retry true-重试, false-不重试
* @return
*/
public static String retryHandler(String requestType, String action, String params, boolean retry){
try {
return requestMethod(requestType,action,params);
} catch (Exception e) {
e.printStackTrace();
if(retry){
try {
Thread.sleep(500);
return requestMethod(requestType,action,params);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
return "-100001"; //服务端接口出错
}

public static void main(String[] args) {
System.out.println("----------------star------------------");
System.out.println(ApiInterface.CHANNEL_INFO);
//String params = "{\"msgheader\":{\"route_id\":\"LZZBGE\",\"route_name\":\"1\",\"login_type\":\"1\",\"mobile\":\"1\",\"timestamp\":\"1\"},\"msgbody\":{\"nonce\":\"1\",\"sign\":\"7BBC156C8D9586E4B874385059FB966F\"}}";
String params = "{\"msgheader\":{},\"msgbody\":{\"keyword\":\"\",\"sign\":\"DAA6320AE7D6C11F369E80808E52A697\"}}";
try {
System.out.println(requestMethod(HTTP_POST,ApiInterface.PRODUCT_LIST,params));
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception");
}
System.out.println("----------------end------------------");
}


}
### Java HTTP 请求工具类或库 对于发送HTTP请求,在Java中有多种方式可以选择。一种常见的做法是使用`HttpURLConnection`,这是JDK自带的一个API[^3]。 ```java URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); int responseCode = conn.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); ``` 除了上述原生的方式外,还可以考虑更高级别的抽象库来简化开发工作量并提高效率。例如Apache HttpClient就是一个非常流行的选择[^2]: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet("http://target.example.org/"); CloseableHttpResponse response = httpClient.execute(request); try { System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); // do something useful with the response body EntityUtils.consume(entity); } finally { response.close(); } httpClient.close(); ``` 另外Spring框架下的`RestTemplate`也提供了便捷的操作接口用于发起RESTful服务调用: ```java RestTemplate restTemplate = new RestTemplate(); String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl, String.class); System.out.println(response.getBody()); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值