搜索URL中的中文字符编码

时间:2018-01-10 11:11:04

标签: java encoding character retrofit2

我正在使用改造在我的Android应用程序中为elasticsearch构建搜索请求。以下是我的代码:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);
    HashMap<String, String> headerMap = new HashMap<>();
    headerMap.put("Authorization", Credentials.basic("user", elasticSearchPassword));

    String searchString = "title:"+ title;
    Call<HitsObject> call = searchAPI.search(headerMap, "AND", searchString);

根据elasticsearch回复,我发现该网址变为:url=http://35.xxx.xxx.48//elasticsearch/hashtags/hashtag/_search?default_operator=AND&q=title:%E6%B5%B7%E5%BA%95%E6%8D%9E%E7%81%AB%E9%94%85

但是我传入的title是一个有效的中文字符串。我怎么解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:1)

假设您使用utf-8编码。

String encodedUrl = "http://35.xxx.xxx.48//elasticsearch/hashtags/hashtag/_search?default_operator=AND&q=title:%E6%B5%B7%E5%BA%95%E6%8D%9E%E7%81%AB%E9%94%85";
String originalUrl = URLDecoder.decode(encodedUrl, "utf-8");
System.out.println(originalUrl);