java发送get请求到另一个程序并传参
时间: 2023-05-04 16:02:15 浏览: 58
Java发送GET请求到另一个程序可以使用URL和HttpURLConnection对象实现。首先,我们需要创建URL对象,指定目标程序的地址和参数。然后,我们可以使用HttpURLConnection对象发送GET请求,设置请求参数和请求头。最后,我们可以解析响应结果并进行处理。
以下是示例代码:
```
import java.net.*;
import java.io.*;
public class GetRequest {
public static void main(String[] args) {
String url = "http://example.com/api";
String charset = "UTF-8";
String param1 = "?key1=value1";
String param2 = "&key2=value2";
try {
URL apiUrl = new URL(url + param1 + param2);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestMethod("GET");
BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseLine;
while ((responseLine = responseReader.readLine()) != null) {
System.out.println(responseLine);
}
responseReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们使用URL对象设置目标程序的地址和参数,使用HttpURLConnection对象发送GET请求,并在响应中读取数据。我们还设置了请求头的编码,并处理了可能的异常情况。