我有一个 URL 列表,我需要获取其中的内容。 URL带有特殊字符,需要进行编码。 我使用 Commons HtpClient 获取内容。
当我使用时:
GetMethod get = new GetMethod(url);
我收到“无效的”非法转义字符“异常。 当我使用
GetMethod get = new GetMethod();
get.setURI(new URI(url.toString(), false, "UTF-8"));
我在尝试获取页面时收到 404,因为空格被转换为 %2520
而不是 %20
。
我看过很多关于这个问题的帖子,其中大部分建议逐个构建 URI。问题是它是给定的 URL 列表,而不是我可以手动处理的列表。
这个问题还有其他解决方案吗?
谢谢。
最佳答案
如果你从它的字符串创建一个新的 URL 对象,比如 URL urlObject = new URL(url)
,然后执行 urlObject.getQuery()
和 urlObject .getPath()
将其正确拆分,将查询参数解析为 List 或 Map 或类似的东西,然后执行类似的操作:
编辑: 我刚刚发现 HttpClient 库有一个 URLEncodedUtils.parse()
方法,您可以通过下面提供的代码轻松使用该方法。我会对其进行编辑以适合,但未经测试。
对于 Apache HttpClient,它会是这样的:
URI urlObject = new URI(url,"UTF-8");
HttpClient httpclient = new DefaultHttpClient();
List<NameValuePair> formparams = URLEncodedUtils.parse(urlObject,"UTF-8");
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
HttpPost httppost = new HttpPost(urlObject.getPath());
httppost.setEntity(entity);
httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity2 = response.getEntity();
对于 Java URLConnection,它将类似于:
// Iterate over query params from urlObject.getQuery() like
while(en.hasMoreElements()){
String paramName = (String)en.nextElement(); // Iterator over yourListOfKeys
String paramValue = yourMapOfValues.get(paramName); // replace yourMapOfNameValues
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
try{
URL u = new URL(urlObject.getPath()); //here's the url path from your urlObject
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(str);
pw.close();
BufferedReader in = new BufferedReader(new
InputStreamReader(uc.getInputStream()));
String res = in.readLine();
in.close();
// ...
}
关于java - 使用 httpclient 进行 URL 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11667062/