說明
Java調(diào)用HTTP接口可以使用Java的HttpURLConnection或HttpClient等工具文章來源地址http://www.zghlxwxcb.cn/news/detail-714668.html
HttpURLConnection
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpExample {
public static void main(String[] args) throws Exception {
// 創(chuàng)建URL對(duì)象
URL url = new URL("http://example.com/api");
// 創(chuàng)建HttpURLConnection對(duì)象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 設(shè)置請(qǐng)求方法為GET
conn.setRequestMethod("GET");
// 發(fā)送請(qǐng)求
int responseCode = conn.getResponseCode();
// 讀取響應(yīng)內(nèi)容
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印響應(yīng)內(nèi)容
System.out.println(response.toString());
}
}
HttpClient
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 java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpExample {
public static void main(String[] args) throws Exception {
// 創(chuàng)建HttpClient對(duì)象
HttpClient client = HttpClientBuilder.create().build();
// 創(chuàng)建HttpGet對(duì)象
HttpGet request = new HttpGet("http://example.com/api");
// 發(fā)送請(qǐng)求
HttpResponse response = client.execute(request);
// 讀取響應(yīng)內(nèi)容
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String inputLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseBuffer.append(inputLine);
}
in.close();
// 打印響應(yīng)內(nèi)容
System.out.println(responseBuffer.toString());
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-714668.html
到了這里,關(guān)于Java調(diào)用HTTP接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!