共计 1853 个字符,预计需要花费 5 分钟才能阅读完成。
Java 可以使用多种方式调用 RESTful 接口,以下是其中几种常见的方法:
- 使用 Java 原生的 HttpURLConnection 类来发送 HTTP 请求:
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 或 OkHttp:
使用 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();
}
}
}
这些示例代码可以根据具体的需求进行修改和扩展。
丸趣 TV 网 – 提供最优质的资源集合!
正文完