亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

java如何調用rest接口

小億
146
2024-04-12 09:32:06
欄目: 編程語言

在Java中調用REST接口通常使用HttpURLConnection或HttpClient來發送HTTP請求并接收響應。以下是一個簡單的示例代碼:

使用HttpURLConnection:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://example.com/api/resource");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用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 org.apache.http.util.EntityUtils;

public class RestClient {

    public static void main(String[] args) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet("http://example.com/api/resource");
        request.addHeader("Content-Type", "application/json");

        try {
            HttpResponse response = httpClient.execute(request);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上述代碼示例使用GET方法調用REST接口,并輸出響應內容。根據實際情況,您可能需要修改HTTP方法、請求頭或請求體等參數。

0
肇州县| 双流县| 图木舒克市| 新巴尔虎左旗| 平塘县| 类乌齐县| 华容县| 平度市| 阿图什市| 东阿县| 嘉兴市| 广河县| 九寨沟县| 涟源市| 吴旗县| 宁国市| 麻江县| 永和县| 康平县| 获嘉县| 高安市| 遂溪县| 大悟县| 宜昌市| 沙洋县| 建湖县| 诸城市| 沙湾县| 曲松县| 黄平县| 安义县| 依安县| 富平县| 宽甸| 临洮县| 九江市| 宽城| 铁力市| 丁青县| 长垣县| 富蕴县|