Java如何发送HTTP POST请求?
以下代码段将向您展示如何使用ApacheHttpComponents发送HTTP发布请求。我们将http://localhost:8080/register使用将该请求发送给,其中包含一些参数NameValuePair。
要将这个参数传递给HTTP发布请求,我们创建的实例,UrlEncodedFormEntity并将的列表NameValuePair作为参数传递。在执行请求之前,我们将此实体对象设置为HttpPost.setEntity()方法。
让我们看下面的代码:
package org.nhooo.example.httpclient; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; 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.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HttpPostExample { public static void main(String[] args) { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("http://localhost:8080/register"); //为HttpPost参数创建一些NameValuePair List<NameValuePair> arguments = new ArrayList<>(3); arguments.add(new BasicNameValuePair("username", "admin")); arguments.add(new BasicNameValuePair("firstName", "System")); arguments.add(new BasicNameValuePair("lastName", "Administrator")); try { post.setEntity(new UrlEncodedFormEntity(arguments)); HttpResponse response = client.execute(post); //打印出响应消息 System.out.println(EntityUtils.toString(response.getEntity())); } catch (IOException e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/httpcomponents/httpclient/4.5.9/httpclient-4.5.9.jar --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.9</version> </dependency>