import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkAPIUtils {
/**
* 发送GET请求
* @param url 请求的URL
* @return 响应结果
* @throws IOException
*/
public static String sendGetRequest(String url) throws IOException {
String result = "";
HttpURLConnection conn = null;
InputStream is = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000); // 设置连接超时
conn.setReadTimeout(5000); // 设置读取超时
conn.connect(); // 建立连接
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
result += new String(buffer, 0, len);
}
}
} finally {
if (is != null) {
is.close();
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
/**
* 发送POST请求
* @param url 请求的URL
* @param postData POST请求体数据
* @return 响应结果
* @throws IOException
*/
public static String sendPostRequest(String url, String postData) throws IOException {
String result = "";
HttpURLConnection conn = null;
InputStream is = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000); // 设置连接超时
conn.setReadTimeout(5000); // 设置读取超时
conn.setDoOutput(true); // 设置该连接是可以输出数据
conn.setRequestProperty("Content-Type", "application/json"); // 设置请求头的内容类型
conn.connect(); // 建立连接
conn.getOutputStream().write(postData.getBytes()); // 发送POST请求体数据
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
result += new String(buffer, 0, len);
}
}
} finally {
if (is != null) {
is.close();
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
}
使用方法
try {
// 发送GET请求
String url1 = "https://webapi.domcer.com/match/mw";
String response1 = NetworkAPIUtils.sendGetRequest(url1);
System.out.println(response1);
// 发送POST请求
String url2 = "https://jsonplaceholder.typicode.com/posts";
String postData = "{\"title\": \"foo\",\"body\": \"bar\",\"userId\": 1}";
String response2 = NetworkAPIUtils.sendPostRequest(url2, postData);
System.out.println(response2);
} catch (IOException e) {
e.printStackTrace();
}