java 调用http接口
时间: 2023-11-20 14:06:41 浏览: 61
http_java调用
Java可以通过调用HttpURLConnection或者HttpClient等类库来实现调用Http接口。
以下是使用HttpURLConnection的示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET"); // 设置请求方法为GET
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(content.toString()); // 输出接口返回的内容
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
以上代码中,我们首先创建了一个URL对象,然后使用该对象创建HttpURLConnection对象。设置请求方法为GET,然后获取接口返回的状态码和内容,并将内容输出。
如果需要发送POST请求,可以将请求方法设置为POST,并设置请求参数。示例代码如下:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class HttpUrlConnectionPostExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST"); // 设置请求方法为POST
con.setDoOutput(true); // 允许输出
String data = "param1=" + URLEncoder.encode("value1", "UTF-8") + "¶m2=" + URLEncoder.encode("value2", "UTF-8");
OutputStream os = con.getOutputStream();
os.write(data.getBytes("UTF-8"));
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(content.toString()); // 输出接口返回的内容
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
以上代码中,我们首先将请求方法设置为POST,并允许输出。然后设置请求参数并将参数写入输出流中,最后获取接口返回的状态码和内容,并将内容输出。
阅读全文