java http post传参
时间: 2023-10-05 10:06:14 浏览: 91
在 Java 中使用 HTTP POST 请求传递参数可以使用 HttpURLConnection 或 HttpClient 客户端库。以下是使用 HttpURLConnection 的示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpPostExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/post");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
String parameters = "param1=value1¶m2=value2";
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(parameters);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用 HttpURLConnection 发送 HTTP POST 请求。我们设置请求方法为 POST,设置 Content-Type 为 application/x-www-form-urlencoded(这是 HTTP POST 请求默认的 Content-Type),设置 setDoOutput 为 true,以便我们可以向服务器发送参数。然后,我们将参数作为字符串写入输出流中,并刷新流。最后,我们从服务器读取响应。
如果您想使用 HttpClient 客户端库进行 HTTP POST 请求,请参考以下示例代码:
```
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpPostExample {
public static void main(String[] args) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/post");
String parameters = "param1=value1¶m2=value2";
StringEntity entity = new StringEntity(parameters);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
System.out.println(EntityUtils.toString(responseEntity));
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用 HttpClient 客户端库发送 HTTP POST 请求。我们创建一个 CloseableHttpClient 对象,然后创建一个 HttpPost 对象并设置请求 URL。我们将参数作为字符串创建 StringEntity 对象,并设置为 HttpPost 的实体。最后,我们执行 HTTP POST 请求,并从服务器读取响应。
阅读全文