java 将通过配置的方法调用远程接口
时间: 2023-02-19 14:50:21 浏览: 58
在 Java 中,可以使用 Java 内置的 HttpURLConnection 类或第三方的 HTTP 客户端库,如 Apache HttpClient、OkHttp 等,来调用远程接口。
以 Apache HttpClient 为例,下面是一个示例代码:
```
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpGet request = new HttpGet("http://www.example.com");
HttpResponse response = httpClient.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
} finally {
httpClient.close();
}
}
}
```
如果是使用 OkHttp,代码示例如下:
```
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.com")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
```
请注意,上面的代码只是一个示例,在实际应用中可能需要根据实际需求进行更多的配置和处理。