jav中httpClient请求接口示例

发布时间 2023-03-27 12:09:31作者: 阿迪di
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientExample {

    public static void main(String[] args) throws IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        String url = "http://example.com/api/v1/user";

        String requestBody = "{\"username\":\"john.doe\",\"email\":\"john.doe@example.com\"}";

        HttpPost request = new HttpPost(url);
        request.setHeader("Content-type", "application/json");
        request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

        HttpResponse response = httpClient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        String responseBody = EntityUtils.toString(response.getEntity());

        System.out.println("Status code: " + statusCode);
        System.out.println("Response body: " + responseBody);
    }

}