91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

Java怎么調用第三方http接口

小億
110
2023-08-17 10:17:13
欄目: 編程語言

Java可以通過以下幾種方式調用第三方HTTP接口:

  1. 使用Java內置的HttpURLConnection類:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClient {
public static void main(String[] args) {
try {
// 創建URL對象
URL url = new URL("http://example.com/api");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設置請求方法
connection.setRequestMethod("GET");
// 發送請求
int statusCode = connection.getResponseCode();
if (statusCode == 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.toString());
} else {
System.out.println("請求失敗,狀態碼:" + statusCode);
}
// 關閉連接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
  1. 使用第三方庫Apache HttpClient:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClient {
public static void main(String[] args) {
try {
// 創建HttpClient對象
HttpClient httpClient = HttpClientBuilder.create().build();
// 創建HttpGet對象
HttpGet httpGet = new HttpGet("http://example.com/api");
// 發送請求并獲取響應
HttpResponse response = httpClient.execute(httpGet);
// 獲取響應實體
HttpEntity entity = response.getEntity();
// 解析實體中的內容
String result = EntityUtils.toString(entity);
// 處理響應
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
  1. 使用第三方庫OkHttp:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpClient {
public static void main(String[] args) {
try {
// 創建OkHttpClient對象
OkHttpClient client = new OkHttpClient();
// 創建Request對象
Request request = new Request.Builder()
.url("http://example.com/api")
.build();
// 發送請求并獲取響應
Response response = client.newCall(request).execute();
// 獲取響應體的內容
String result = response.body().string();
// 處理響應
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

以上是三種常見的Java調用第三方HTTP接口的方式,根據具體情況選擇合適的方式。

0
永新县| 沙雅县| 南平市| 宝山区| 江永县| 青铜峡市| 灯塔市| 嘉禾县| 临西县| 蕉岭县| 莲花县| 尼木县| 赤壁市| 霍邱县| 清原| 崇仁县| 元阳县| 广水市| 如皋市| 汉沽区| 瑞安市| 通江县| 尉犁县| 寿阳县| 临清市| 大余县| 黄骅市| 沧州市| 朝阳县| 玉田县| 黄陵县| 泸溪县| 丽水市| 邵武市| 汤原县| 河东区| 台前县| 济源市| 昭觉县| 桂阳县| 广灵县|