1. 首页
  2. 操作系统
  3. OS
  4. 使用HttpClient进行POST请求的示例

使用HttpClient进行POST请求的示例

上传者: 2023-03-09 03:26:24上传 MD文件 16.3KB 热度 32次
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>
用户评论