java 实现get请求 url传参
时间: 2024-06-09 13:12:21 浏览: 172
java 实现get,post请求
可以使用java中的HttpURLConnection或者HttpClient来实现get请求,同时可以通过URL传递参数。
使用HttpURLConnection实现:
```
import java.net.*;
import java.io.*;
public class HttpGetRequest {
public static void main(String[] args) {
try {
String urlStr = "http://example.com/api?param1=value1¶m2=value2";
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 (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用HttpClient实现:
```
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.utils.URIBuilder;
public class HttpGetRequest {
public static void main(String[] args) {
try {
String urlStr = "http://example.com/api";
URIBuilder builder = new URIBuilder(urlStr);
builder.setParameter("param1", "value1");
builder.setParameter("param2", "value2");
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(builder.build());
request.addHeader("Accept", "application/json");
HttpResponse response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
client.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们通过URL传递了两个参数:param1和param2。您可以根据您的需求添加更多的参数。
阅读全文