使用Java调用RESTful API接口
时间: 2023-12-03 13:05:23 浏览: 144
要使用Java调用RESTful API接口,可以使用Java内置的HttpURLConnection类或者第三方库如Apache HttpClient等。
以下是使用HttpURLConnection类的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestClient {
public static void main(String[] args) throws IOException {
String url = "http://api.example.com/users";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//设置请求方法
con.setRequestMethod("GET");
//添加请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
```
以上代码通过HttpURLConnection发送GET请求,并输出返回的字符串。可以根据需要修改请求方法和添加请求头。
阅读全文