java调用http接口get请求提交参数方式
时间: 2023-04-05 16:03:19 浏览: 129
您好,关于java调用http接口get请求提交参数方式,可以使用以下代码实现:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpGetDemo {
public static void main(String[] args) {
try {
String urlStr = "http://example.com/api?param1=" + URLEncoder.encode("value1", "UTF-8") + "¶m2=" + URLEncoder.encode("value2", "UTF-8");
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,`urlStr`为请求的URL地址,`param1`和`param2`为请求参数名,`value1`和`value2`为请求参数值。使用`URLEncoder.encode`方法对参数值进行编码,以避免出现特殊字符导致的请求失败。使用`HttpURLConnection`类发送GET请求,并设置请求头部信息,如`Accept`。最后,读取响应数据并输出。
阅读全文