2016-06-30 65 views
-2

因此,我在StackOverflow上尋找關於此問題的答案,但找不到一個。Java - 用+符號替換字符串中的所有空格用於URL

我有一個左右部分總是相同的URL,但中間部分不斷變化。如果只有一個單詞它可以正常工作,但是如果有多個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 
+0

string.replace(「」,「+」) 這是將字符串中的所有空格轉換爲+號的基本 –

+3

URLEncoder.encode(String)就是我要這樣做的方式。 –

+0

什麼不適合你的嘗試?輸出是什麼,或者例外? – Tunaki

回答

0

我認爲,這個問題的答案將解決您的問題。

Removing whitespace from strings in Java

你只需要改變從st.replaceAll("\\s","")st.replaceAll("\\s","+"),因爲你需要替換所有空格用加號。

+0

不,不工作 – DaxHR

+0

你有什麼樣的輸入?如果它是一個文本將其放入一個字符串,然後使用'replaceAll'方法。 – Julian

0

我只是使用替換方法。 使用您的「內容」字符串:

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

這將檢查空間和替換加空間。如果由於開始和結束使用整個字符串時,這是一個問題,我只需將中間字符串子串,然後使用replace方法。請嘗試https://docs.oracle.com/javase/7/docs/api/java/lang/String.html以獲取對java中的字符串的所有引用及其預定義的引用。

相關問題