import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUrlConnectionExample { public static void main(String[] args) throws IOException { URL url = new URL("http://api.example.com/user/1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println("Response: " + response.toString()); } else { System.out.println("Error: " + responseCode); } connection.disconnect(); } } 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.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class ApacheHttpClientExample { public static void main(String[] args) throws IOException { String url = "http://api.example.com/user"; String requestBody = "{\"name\": \"John\", \"age\": 25}"; HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.setEntity(new StringEntity(requestBody)); post.setHeader("Content-type", "application/json"); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); System.out.println("Response: " + responseBody); } }


上一篇:
下一篇:
切换中文