在Java中,调用第三方HTTP接口是一种常见的需求,为了实现这一目标,Java提供了多种方式,包括使用原生的HttpURLConnection、Apache HttpClient、OkHttp等库,本文将对Java调用第三方HTTP接口的常用方式进行总结。
1、使用HttpURLConnection
HttpURLConnection是Java标准库中的一个类,用于发送HTTP请求和接收HTTP响应,以下是一个简单的示例:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { public static void main(String[] args) throws Exception { String url = "http://api.example.com/data"; URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } }
2、使用Apache HttpClient
Apache HttpClient是一个开源的HTTP客户端库,提供了丰富的功能和灵活的配置选项,以下是一个简单的示例:
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class ApacheHttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://api.example.com/data"); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); String response = EntityUtils.toString(httpEntity, "UTF-8"); System.out.println(response); } }
3、使用OkHttp
OkHttp是一个高效且易用的HTTP客户端库,由Square公司开发,以下是一个简单的示例:
import okhttp3.*; import java.io.IOException; import java.util.concurrent.TimeUnit; public class OkHttpExample { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "{}"); Request request = new Request.Builder() .url("http://api.example.com/data") .post(body) .addHeader("User-Agent", "OkHttp Example") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); ResponseBody responseBody = response.body(); System.out.println(responseBody.string()); } catch (IOException e) { e.printStackTrace(); } finally { client = null; // 释放资源,避免内存泄漏 } } }
问题与解答:
1、Q: 在使用Apache HttpClient时,如何设置超时时间?
A: 可以通过RequestConfig
对象设置超时时间,RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
,然后将requestConfig
应用到HttpGet
或HttpPost
对象上。
2、Q: 在使用OkHttp时,如何设置代理服务器?
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/172704.html