HttpClient post 请求传参实例
时间: 2023-05-22 15:06:31 浏览: 121
您好,以下是使用 HttpClient 进行 post 请求传参的示例:
```
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
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.client.HttpClient;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
public class Example {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
URIBuilder builder = new URIBuilder("https://example.com/api");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpClient.execute(request);
try {
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(statusCode);
System.out.println(responseBody);
} finally {
response.close();
}
} catch (Exception e) {
System.err.println(e);
} finally {
try {
httpClient.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
}
```
阅读全文