java调用http接口
时间: 2023-10-16 12:09:39 浏览: 20
Java可以通过HttpURLConnection或者Apache HttpComponents等库来调用http接口。
以下是使用HttpURLConnection的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以下是使用Apache HttpComponents的示例代码:
```java
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 HttpComponentsExample {
public static void main(String[] args) {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com/api");
HttpResponse response = client.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意,以上示例代码仅供参考,具体实现应根据具体场景进行调整。