Java可以使用多种方式调用RESTful接口,以下是其中几种常见的方法:
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");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用Apache HttpClient的示例:
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 RestClient {
public static void main(String[] args) {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com/api/resource");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用OkHttp的示例:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RestClient {
public static void main(String[] args) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com/api/resource")
.build();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这些示例代码可以根据具体的需求进行修改和扩展。