java发送http请求工具类
时间: 2023-08-16 07:11:10 浏览: 188
JAVA 发送http请求工具类
好的,以下是一个简单的 Java 发送 HTTP 请求的工具类:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
// 发送 GET 请求
public static String sendGet(String url) {
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
// 发送 POST 请求
public static String sendPost(String url, String param) {
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setDoOutput(true);
conn.getOutputStream().write(param.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
}
```
使用方法示例:
```java
String url = "http://www.example.com/api";
String result = HttpUtil.sendGet(url);
System.out.println(result);
String param = "name=John&age=25";
result = HttpUtil.sendPost(url, param);
System.out.println(result);
```
注:以上代码仅供参考,实际使用时需要根据具体需求进行修改和优化。
阅读全文