如何使用Java编写一个RESTful客户端
如果你需要在Java中使用RESTful API,那么你需要编写一个RESTful客户端。在这篇文章中,我将介绍如何使用Java编写一个RESTful客户端。
首先,我们需要使用Java的HTTP客户端库。有很多可供选择的库,比如Apache HttpComponents、OkHttp等。在这里,我将使用Apache HttpComponents。
创建一个名为RestfulClient.java的文件,添加以下代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class RestfulClient {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/users";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
}
}
用户评论