httpclient 请求post接口
时间: 2023-10-10 20:05:46 浏览: 107
好的,以下是使用Apache HttpClient请求POST接口的示例代码:
```java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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 HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
String requestBody = "{\"name\":\"John\",\"age\":30}";
StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8);
httpPost.setEntity(entity);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
System.out.println("Response: " + responseString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们创建了一个默认的HttpClient实例,然后构造了一个HttpPost请求对象,设置了请求头和请求体,最后发送请求并获取响应。你只需要将请求地址和请求体替换成你的实际接口地址和请求参数即可。
阅读全文