java调用http的工具类_JAVA工具类 [ 调用HTTP 请求 ]
时间: 2023-12-25 15:04:55 浏览: 74
以下是一个示例的Java工具类,可以用于调用HTTP请求。
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
/**
* 发送HTTP GET请求
* @param url 请求的URL
* @return 响应结果
* @throws Exception
*/
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为GET
con.setRequestMethod("GET");
// 获取响应结果
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
/**
* 发送HTTP POST请求
* @param url 请求的URL
* @param postData POST请求的参数
* @return 响应结果
* @throws Exception
*/
public static String sendPost(String url, String postData) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置POST请求的参数
con.setDoOutput(true);
con.getOutputStream().write(postData.getBytes("UTF-8"));
con.getOutputStream().flush();
con.getOutputStream().close();
// 获取响应结果
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
使用示例:
```java
public static void main(String[] args) {
try {
// 发送GET请求
String response = HttpUtil.sendGet("http://www.example.com");
System.out.println(response);
// 发送POST请求
String postData = "param1=value1¶m2=value2";
response = HttpUtil.sendPost("http://www.example.com", postData);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
```
阅读全文