我这段代码在调用sendJsonGet工具类的时候报错了,因为工具类里面拼接的有问号,我代码里面拼接的也有问号,因为请求地址里面有变量,怎么用StringBuffer方法将链接和参数分开拼接啊
图一是代码和报错信息
图二是请求地址和请求参数
下面是调用的工具类,工具类不能修改
public static String sendJsonGet(String url, String path,Map<String, String> headParams) {
String result = "";
BufferedReader in = null;
try {
// 拼接参数,可以用URIBuilder,也可以直接拼接在?传值,拼在url后面
//URIBuilder uriBuilder = new URIBuilder(url);
String psthUrl=URLEncoder.encode(path,"utf-8");
URL realUrl =new URL(url+"?"+psthUrl);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 获取请求头Map
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 设置通用的请求属性\
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
for (String key : headParams.keySet()) {
connection.setRequestProperty(key,headParams.get(key));
}
connection.setConnectTimeout(180000);
connection.setReadTimeout(180000);
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
System.out.println("请求地址 =="+url);
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("发送GET请求出现异常!\r\n" + e);
result = e.toString();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
log.error(e2);
}
}
return result;
}