java 带有包含空格的 URL 的 HttpURLConnection
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26671056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpURLConnection with URL that contains space
提问by Amos
I have a url that one of its params contains a space character. If I send it as is, using HttpURLConnection, this param passes wrongly.
我有一个 url,其中一个参数包含一个空格字符。如果我按原样发送它,使用 HttpURLConnection,这个参数会错误地传递。
If I manually replace the space with %20, it's working as expected so I was wondering if there is a cleaner way to do so though I was hoping that HttpURLConnection will do it automatically. Maybe there is a way that I missed?
如果我用 %20 手动替换空格,它会按预期工作,所以我想知道是否有更简洁的方法来做到这一点,尽管我希望 HttpURLConnection 会自动完成。也许有一种方法我错过了?
When looking for this, I keep bumping into URLEncoder.Encode which is deprecated and I couldn't find any other way to do what I do except for encoding the whole URL, including the :// of the http.
在查找此内容时,我不断遇到已弃用的 URLEncoder.Encode,除了对整个 URL 进行编码(包括 http 的 :// )之外,我找不到任何其他方法来做我所做的事情。
Is there a clean way to do the replacement or should I do it manually?
是否有一种干净的方法来进行更换,还是应该手动进行?
url for example: http://www.domain.com?param1=name'last¶m2=2014-31-10 11:40:00 param 1 contains ' and param2 contains both space and : but only the space makes the problem. This is why I don't understand why HttpUrlConnection is so sensitive for space only.
url 例如:http: //www.domain.com?param1=name 'last¶m2=2014-31-10 11:40:00 param 1 contains ' 和 param2 包含空格和 : 但只有空格才会出现问题。这就是为什么我不明白为什么 HttpUrlConnection 仅对空间如此敏感。
Thanks
谢谢
回答by Haresh Chhelana
Try this way,hope this will help you to solve your problem.
试试这个方法,希望这能帮助你解决你的问题。
URLEncoder: All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') and characters '.', '-', '*', '_' are converted into their hexadecimal value prepended by '%'.
URLEncoder: 除字母 ('a'..'z', 'A'..'Z') 和数字 ('0'..'9') 和字符 '.', '-', '*' 之外的所有字符, '_' 被转换为它们的十六进制值,前面加上 '%'。
In URLEncoder class have two method :
在 URLEncoder 类中有两个方法:
1.encode(String url) : This method was deprecated in API level 1
1.encode(String url) : 此方法在 API 级别 1 中已弃用
String encodedUrl = URLEncoder.encode(url);
2.encode(String url, String charsetName) : Encodes url using the Charset named by charsetName.
2.encode(String url, String charsetName):使用由charsetName命名的Charset对url进行编码。
String encodedUrl = URLEncoder.encode(url,"UTF-8");
How to use :
如何使用 :
String url ="http://www.domain.com";
String param1 ="?param1=";
Strinf param1value ="name'last";
String param2 ="¶m2=";
Strinf param2value ="2014-31-10 11:40:00";
String encodeUrl = url +param1+ URLEncoder.encode(param1value,"UTF-8")+param2+URLEncoder.encode(param2value,"UTF-8");
回答by raj
you can use
您可以使用
String oldurl="http://pairdroid.com/whatsapp.php?a=rajesh saini";
String newurl=oldurl.replaceAll(" ","%20");
URL url = new URL(newurl);
回答by Stanley Shi
As stated in the URLEncoder's javadoc, you should use URLEncoder.encode(String s, String enc)
如 URLEncoder 的 javadoc 中所述,您应该使用 URLEncoder.encode(String s, String enc)
回答by Tushski
Instead of using HttpURLConnection why don't you use HttpClient class with HttpPost class. This way you avoid the tension of URL encoding. Below is an example on how to it:
而不是使用 HttpURLConnection 为什么不使用 HttpClient 类和 HttpPost 类。这样您就可以避免 URL 编码的紧张。以下是有关如何操作的示例:
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR URL);
try {
ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PARAMETER1, VALUE1));
nameValuePairs.add(new BasicNameValuePair(PARAMETER2, VALUE2));
...
nameValuePairs.add(new BasicNameValuePair(PARAMETERn, VALUEn));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
EDIT:
编辑:
String result = "";
URL url = new URL(YOUR URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PARAMETER1, VALUE1));
nameValuePairs.add(new BasicNameValuePair(PARAMETER2, VALUE2));
...
nameValuePairs.add(new BasicNameValuePair(PARAMETERn, VALUEn));
//Send request
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getUrlParameters(params));
writer.flush();
writer.close();
os.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null) {
response.append(line);
response.append('\r');
}
r.close();
result = response.toString();
conn.disconnect();
Code for getUrlParameters() method:
getUrlParameters() 方法的代码:
private String getUrlParameters(List<NameValuePair> params) throws UnsupportedEncodingException{
StringBuilder parameter = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
parameter.append(URLEncoder.encode(pair.getName(), "UTF-8"));
parameter.append("=");
parameter.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
parameter.append("&");
}
return parameter.toString().substring(0, parameter.length()-2);
}
But my initial approach is very easy to implement and has never failed me not even once. As for which approach you wish to use totally up to you, weather you go with HttpURLConnection (Android recommended approach) or the other one.
但是我最初的方法很容易实施,而且从来没有让我失望过一次。至于您希望使用哪种方法完全取决于您,您可以使用 HttpURLConnection(Android 推荐的方法)或其他方法。