HttpClient 发送Post,Get请求例子(包含设置请求头信息和获取返回头信息)
时间: 2024-01-05 15:05:02 浏览: 56
利用HttpClient发送HTTP请求
以下是 HttpClient 发送 Post 请求和设置请求头信息的示例:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://www.example.com/api");
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("key1", "value1"));
parameters.add(new BasicNameValuePair("key2", "value2"));
request.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
System.out.println(responseText);
// 获取返回头信息
String contentType = response.getFirstHeader("Content-Type").getValue();
System.out.println(contentType);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
以下是 HttpClient 发送 Get 请求和获取返回头信息的示例:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpGet request = new HttpGet("http://www.example.com/api");
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
System.out.println(responseText);
// 获取返回头信息
String contentType = response.getFirstHeader("Content-Type").getValue();
System.out.println(contentType);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
阅读全文