使用JAVA.NET包中的HttpURLConnection类。以下是一个简单的示例代码,用于发送GET请求并获取响应:
javaCopy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequestExample {
public static void mAIn(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 获取响应代码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.Append(line);
}
reader.close();
// 打印响应内容
System.out.println("Response: " + response.toString());
// 断开连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述示例代码用于发送GET请求,您可以更改请求方法和URL以适应您的实际需求。请注意,HTTP请求是不安全的,建议在实际使用中使用HTTPS来确保数据的安全传输。
使用Apache HttpClient库。请确保您的项目中包含了相关的依赖
示例代码:
javaCopy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpsPostRequestExample {
public static void main(String[] args) {
try {
// 创建HttpClient对象
HttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象,并设置URL
HttpPost httpPost = new HttpPost("https://example.com");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
String requestBody = "{"key1":"value1","key2":"value2"}";
StringEntity requestEntity = new StringEntity(requestBody);
httpPost.setEntity(requestEntity);
// 发送POST请求
HttpResponse response = httpClient.execute(httpPost);
// 获取响应代码
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseContent = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
// 打印响应内容
System.out.println("Response: " + responseContent.toString());
// 断开连接
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述示例代码中,我们使用了Apache HttpClient库来发送HTTPS的POST请求。您可以根据实际需求修改请求的URL、请求头、请求体等部分。请确保您的项目中包含了Apache HttpClient库的依赖。