Java可以通過以下幾種方式調用第三方HTTP接口:
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();
}
}
}
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();
}
}
}
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接口的方式,根據具體情況選擇合適的方式。