【问题标题】:Java - replace all blank space in String with + sign for URLJava - 将字符串中的所有空格替换为 URL 的 + 号
【发布时间】:2016-11-03 04:22:36
【问题描述】:

所以我在 StackOverflow 上寻找这个问题的答案,但找不到。

我有一个网址,其左右部分始终相同,但中间部分不断变化。如果只有一个词,它可以正常工作,但如果有多个 URL 会中断。

我需要用加号 (+) 替换所有空格。

我没有运气使用此代码:

String content = bioObj.getString("summary");
                    content = content.replaceAll(" ", "%20");
                    bio.setText(content);

谁能帮忙?

完整代码:

String finalUrlBio = bioUrlLeft+title+bioUrlRight;

        JsonObjectRequest bioRequest = new JsonObjectRequest(Request.Method.GET, finalUrlBio, (JSONObject) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject artistObj = response.getJSONObject("artist");
                    JSONObject bioObj = artistObj.getJSONObject("bio");
                    String content = bioObj.getString("summary");
                    content = content.replaceAll("\\s","+");
                    bio.setText(content);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        AppController.getInstance().addToRequestQueue(bioRequest);

错误:

07-01 00:00:37.379 2793-2872/com.darioradecic.topmusicandartists E/Volley: [397649] BasicNetwork.performRequest: Unexpected response code 400 for http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Red Hot Chili Peppers&api_key=99b9ea4e41463638c76b4759d8b1da1d&format=json

【问题讨论】:

  • string.replace(" ","+") 这是将字符串中的所有空格转换为+号的基础
  • URLEncoder.encode(String) 是我会这样做的方式。
  • 您的尝试有什么问题?输出是什么,还是异常?
  • Rakshit 不,收到此错误:意外响应代码 400
  • Ellitot 不,同样的错误,.encode 已弃用

标签: java android json string


【解决方案1】:

我只会使用替换方法。 使用您的“内容”字符串:

content.replace(' ', '+');

这将检查空格并用加号替换空格。如果由于开头和结尾而在使用整个字符串时出现问题,我将简单地对中间进行子字符串化,然后使用替换方法。尝试 https://docs.oracle.com/javase/7/docs/api/java/lang/String.html 获取对 java 中字符串的所有引用及其预定义引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2013-01-04
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2013-11-21
    相关资源
    最近更新 更多