java url中的参数执行POST ?
时间: 2024-05-14 18:12:31 浏览: 111
java 实现通过 post 方式提交json参数操作
Java中可以使用HttpURLConnection或者HttpClient来执行POST请求,将参数放在请求体中。以下是使用HttpURLConnection的示例代码:
```java
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String param1 = "value1";
String param2 = "value2";
String postData = "param1=" + URLEncoder.encode(param1, "UTF-8") +
"¶m2=" + URLEncoder.encode(param2, "UTF-8");
OutputStream outputStream = conn.getOutputStream();
outputStream.write(postData.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
// 处理响应数据
inputStream.close();
}
```
使用HttpClient的示例代码:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
String param1 = "value1";
String param2 = "value2";
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", param1));
params.add(new BasicNameValuePair("param2", param2));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
// 处理响应数据
EntityUtils.consume(entity);
}
response.close();
```
阅读全文