需要确定以下几点:
以下是一个使用 HttpClient 发送 GET 请求的示例代码:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://jsonplaceholder.typicode.com/posts");
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
String responseString = EntityUtils.toString(httpResponse.getEntity());
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("Response status code: " + statusCode);
System.out.println("Response body: " + responseString);
httpClient.close();
}
}
在此示例中,我们使用了 HttpClients 创建了一个 HttpClient。然后,我们使用 HttpGet 创建了一个 GET 请求,并将其发送到“https://jsonplaceholder.typicode.com/posts”端点。发送请求后,我们获取响应并将其转换为字符串格式。最后,我们打印了响应状态代码和响应正文。确保我们在 URL 中使用的是 HTTPS,而不是 HTTP,可能需要在代码中指定代理,并处理异常。