2

我正在研究西班牙语版本的搜索,当用户输入西班牙语字符(比如 HÍBRIDOS)时,我会看到一些异常(如下所示)。显示我如何在下面编码。发送的 url 是通过网络发送的,如图所示。

url=http://wwwdev.searchbridg.com/absd/JSONControllerServlet.do?&N=0&Ntk=AllText&Ntt=HÃBRIDOS&Nty=1&Ntx=mode+matchall

  DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    try {
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    HttpHost proxy = new HttpHost(getProxy(), getProxyPort());
    ConnRouteParams.setDefaultProxy(params, proxy);
    URI uri;
    InputStream data = null;
        uri = new URI(url);
        HttpGet method = new HttpGet(uri);
        HttpResponse response=null;
        try {
        response = httpClient.execute(method);
        }catch(Exception e) {
            e.printStackTrace();
            throw e;
        }
        data = response.getEntity().getContent();
    Reader r = new InputStreamReader(data);
    HashMap<String, Object> jsonObj = (HashMap<String, Object>) GenericJSONUtil.fromJson(r);

java.net.URISyntaxException: Illegal character in query at index 101: http://wwwdev.searchbridge.com/abs/JSONControllerServlet.do?&N=0&Ntk=AllText&Ntt=H├?BRIDOS&Nty=1&Ntx=mode+matchall
    at java.net.URI$Parser.fail(URI.java:2816)
    at java.net.URI$Parser.checkChars(URI.java:2989)
    at java.net.URI$Parser.parseHierarchical(URI.java:3079)
    at java.net.URI$Parser.parse(URI.java:3021)
    at java.net.URI.<init>(URI.java:578)

我尝试使用 UTF-8 编码进行编码,但仍然无法正常工作,显示相同的异常。html页面设置为<meta charset="utf-8" />

byte[] bytes = url.getBytes("UTF8");
    String stringuRL = new String(bytes,"UTF-8");
        uri = new URI(stringuRL);
4

2 回答 2

4

如果您在请求时发送特殊字符(GET 请求),则必须对它们进行 URLescape。查看此线程以了解如何操作。Java中的HTTP URL地址编码

当您收到请求时,您必须执行相反的过程才能获得原始单词。

于 2012-06-15T14:49:55.550 回答
1

get 请求中的所有参数都需要对其值进行编码。

如果您使用的是 HTTPClient 4,您可以或多或少地这样做:

List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("parameter_name_Ã", "another value with ~ãé"));
parameters.add(new BasicNameValuePair("second_parameter", "still other ú û"));
String url = "http://foo.bar/?" + URLEncodedUtils.format(parameters, "UTF-8");

这个案例的结果将是http://foo.bar/?parameter_name_%C3%83=another+value+with+%7E%C3%A3%C3%A9&second_parameter=still+other+%C3%BA+%C3%BB

于 2012-06-15T14:59:18.000 回答