java 请求url拼接多个参数
时间: 2024-09-10 12:10:29 浏览: 59
在Java中,请求URL拼接多个参数通常使用`HttpURLConnection`、`HttpClient`或者其他HTTP客户端库。这里我将演示如何使用最基础的`HttpURLConnection`来构建一个包含多个参数的GET请求URL:
```java
import java.net.URL;
import java.net.HttpURLConnection;
public class URLBuilder {
private static final String PARAM_SEPARATOR = "&"; // 参数分隔符
public static void main(String[] args) {
String baseUrl = "http://example.com/api";
String key1 = "value1";
String key2 = "value2";
String key3 = "value3";
// 构造查询字符串
String queryParameters = key1 + "=" + urlEncode(key1) + PARAM_SEPARATOR +
key2 + "=" + urlEncode(key2) + PARAM_SEPARATOR +
key3 + "=" + urlEncode(key3);
// 构建完整的URL
URL url = new URL(baseUrl + "?" + queryParameters);
try (HttpURLConnection connection = (HttpURLConnection) url.openConnection()) {
// 设置请求方法(这里是GET)
connection.setRequestMethod("GET");
// 打开连接并获取响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
e.printStackTrace();
}
}
// 将字符串转换为URL编码,避免特殊字符导致的问题
private static String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // 程序中不应出现这种情况,但这里为了示例完整性
}
}
}
```
阅读全文