使用httpclient进行URL编码

use*_*654 6 java encoding apache-httpclient-4.x

我有一个URL列表,我需要获取其中的内容.URL具有特殊字符,因此需要进行编码.我使用Commons HtpClient来获取内容.

我用的时候:

GetMethod get = new GetMethod(url);
Run Code Online (Sandbox Code Playgroud)

我得到一个"无效的"非法转义字符"例外.当我使用时

 GetMethod get = new GetMethod();
 get.setURI(new URI(url.toString(), false, "UTF-8"));
Run Code Online (Sandbox Code Playgroud)

我试图获取页面时得到404,因为空间被转向%2520而不仅仅是%20.

我已经看过很多关于这个问题的帖子,他们中的大多数建议逐个部分地构建URI.问题是它是一个给定的URL列表,而不是我可以手动处理的URL.

解决这个问题的任何其他方案?

谢谢.

hec*_*g87 5

如果你创建一个新的URL对象从它的串像URL urlObject = new URL(url),然后做urlObject.getQuery()urlObject.getPath()右拆呢,解析查询参数到列表或地图或东西,这样做:

编辑:我刚刚发现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();
Run Code Online (Sandbox Code Playgroud)

使用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();
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Yai*_*sky -1

请使用URLEncoder类。
我在一个确切的场景中使用了它,它对我来说效果很好。
我所做的是使用 URL 类,获取主机后面的部分
(例如 - 在 www.bla.com/mystuff/bla.jpg 这将是“mystuff/bla.jpg” - 你应该只进行 URLEncode这部分,然后重新构造URL,

例如,如果原始字符串是“http://www.bla.com/mystuff/bla foo.jpg”,则:
Encode - “mystuff/bla foo.jpg”并得到“mystuff/bla%20foo.jpg”,然后将其附加到主机和协议部分:
“http://www.bla.com/mystuff/bla%20foo.jpg”
我希望这会有所帮助

  • 尽管名称如此,URLEncoder 并不用于对 URL 进行编码。它用于编码 html mime 附件。 (3认同)