使用HttpClient进行POST请求的示例
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
public class HttpClientPostExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api/post");
List params = new ArrayList<>();
params.add(new BasicNameValuePair("username", "myusername"));
params.add(new BasicNameValuePair("password", "mypassword"));
httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
System.out.println(responseBody);
} finally {
response.close();
}
}
}
</basicnamevaluepair>
用户评论