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\":\"[email protected]\"}"; 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); } }
标签:http,String,示例,jav,org,apache,import,httpClient From: https://www.cnblogs.com/shendidi/p/17261114.html