java中 post请求传递string
时间: 2023-11-18 18:02:38 浏览: 46
在Java中,可以使用HttpURLConnection或HttpClient来发送POST请求并传递字符串参数。
使用HttpURLConnection的示例代码如下:
```java
URL url = new URL("http://example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
String requestBody = "{\"param1\":\"value1\",\"param2\":\"value2\"}";
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(requestBody.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
```
使用HttpClient的示例代码如下:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
StringEntity requestBody = new StringEntity("{\"param1\":\"value1\",\"param2\":\"value2\"}");
requestBody.setContentType("application/json");
httpPost.setEntity(requestBody);
CloseableHttpResponse response = httpClient.execute(httpPost);
int responseCode = response.getStatusLine().getStatusCode();
```
这两个示例中,都是将字符串参数作为JSON格式的请求体发送到服务器端,可以根据具体需求修改请求体的内容格式。