共計(jì) 1482 個(gè)字符,預(yù)計(jì)需要花費(fèi) 4 分鐘才能閱讀完成。
在 Java 中調(diào)用 REST 接口通常使用 HttpURLConnection 或 HttpClient 來(lái)發(fā)送 HTTP 請(qǐng)求并接收響應(yīng)。以下是一個(gè)簡(jiǎn)單的示例代碼:
使用 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 方法調(diào)用 REST 接口,并輸出響應(yīng)內(nèi)容。根據(jù)實(shí)際情況,您可能需要修改 HTTP 方法、請(qǐng)求頭或請(qǐng)求體等參數(shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完