【问题标题】:Space between http url in javajava中http url之间的空格
【发布时间】:2013-10-09 18:52:44
【问题描述】:

这段代码运行良好

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:8090/Servlet/ServletFirst?to=1234&from=567&text=testtest");

如果我在参数值之间使用空格。它抛出异常

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:8090/Servlet/ServletFirst?to=1234&from=567&textParam=test test");

测试测试之间的空格会引发错误。如何解决?

【问题讨论】:

标签: java


【解决方案1】:

使用

URLEncoder.encode("test test","UTF-8")

所以把你的代码改成

HttpGet request = new HttpGet("http://localhost:8090/Servlet/ServletFirst?to=1234&from=567&textParam="+URLEncoder.encode("test test","UTF-8"));

注意 不要Encode整个网址

URLEncoder.encode("http://...test"); // its Wrong because it will also encode the // in http://

【讨论】:

    【解决方案2】:

    使用%20 表示URL 中的空格,因为空格不是允许的字符。在 URL 中查看 the Wikipedia entry for character data

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(
        "http://localhost:8090/Servlet/ServletFirst?to=1234&from=567&textParam=test%20test");
    

    【讨论】:

      【解决方案3】:

      您必须对 URL 中的参数进行 URL 编码;使用%20 代替空格。

      HttpGet request = new HttpGet("http://localhost:8090/Servlet/ServletFirst?to=1234&from=567&textParam=test%20test");
      

      Java 有一个类可以为你做 URL 编码,URLEncoder:

      String param = "test test";
      String enc = URLEncoder.encode(param, "UTF-8");
      
      String url = "http://...&textParam=" + enc;
      

      【讨论】:

        【解决方案4】:

        只需使用%20 来表示空格。

        这是 URL 编码的全部部分:http://www.w3schools.com/tags/ref_urlencode.asp

        所以你会想要:

        HttpGet request = new HttpGet("http://localhost:8090/Servlet/ServletFirst?to=1234&from=567&text=test%20test");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-04
          • 2013-06-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-27
          • 1970-01-01
          相关资源
          最近更新 更多