2015-09-23 60 views
5

發送POST請求與JSONArray我想在Android中發送一個簡單的POST請求與身體等於這個:使用凌空

[ 
{ 
    "value": 1 
} 
] 

我試圖在Android中使用排庫,這是我的代碼:

// the jsonArray that I want to POST  
String json = "[{\"value\": 1}]"; 
JSONArray jsonBody = null; 
try { 
    jsonBody = new JSONArray(json); 
    } catch (JSONException e) { 
           e.printStackTrace(); 
           } 
final JSONArray finalJsonBody = jsonBody; 

// starting the request 
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); 
JsonObjectRequest request = 
new JsonObjectRequest(com.android.volley.Request.Method.POST,"https://...",null, 

new Response.Listener<JSONObject>() { 

@Override 
public void onResponse(JSONObject response) { 
Log.d("mytag", "Response is: " + response);}}, 
new Response.ErrorListener() { 

@Override 
public void onErrorResponse(VolleyError error) { 
Log.d("Mytag", "error");}}) { 

@Override 
protected Map<String,String> getParams() { 
// the problem is here... 
return (Map<String, String>) finalJsonBody; 
} 

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
HashMap<String, String> params = new HashMap<String, String>(); 
// I put all my headers here like the following one : 
params.put("Content-Type", "application/json");          
return params;}}; 

queue.add(request); 

問題是getParams方法只接受一個Map對象,因爲我想發送一個JSONArray。所以,我不得不使用鑄造,其產生的錯誤,那麼......

我不知道我怎麼能解決這個問題 謝謝

+0

閱讀[我asnwer這裏(http://stackoverflow.com /問題/ 32197615 /抽射,發送-的JSONObject到服務器與 - 法柱/ 32216762#32216762)。但是,您的json是JSONArray,而不是JSONObject。 – BNK

+0

你可以更明白嗎?我仍然無法編碼這個jsonArray ...謝謝你的理解 – fujitsu4

+0

JSONObject jsonBody = new JSONObject(「{\」value \「:1}」); JSONObject以{開始並以}結尾。而且,你得到了什麼錯誤信息?請發佈它和任何logcat信息(如果可用)。 – BNK

回答

4

你可以參考我下面的示例代碼:

更新您的引擎收錄鏈接:

由於服務器響應的JSONArray,我用JsonArrayRequest代替JsonObjectRequest。並且不需要覆蓋getBody了。

 mTextView = (TextView) findViewById(R.id.textView); 
     String url = "https://api.orange.com/datavenue/v1/datasources/2595aa553d3049f0b0f03fbaeaa7ddc7/streams/9fe5edb1c76e4968bdcc9c902010bc6c/values"; 
     RequestQueue requestQueue = Volley.newRequestQueue(this); 
     final String jsonString = "[\n" + 
       " {\n" + 
       " \"value\": 1\n" + 
       " }\n" + 
       "]"; 
     try { 
      JSONArray jsonArray = new JSONArray(jsonString); 
      JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, jsonArray, new Response.Listener<JSONArray>() { 
       @Override 
       public void onResponse(JSONArray response) { 
        mTextView.setText(response.toString()); 
       } 
      }, new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        mTextView.setText(error.toString()); 
       } 
      }) { 
       @Override 
       public Map<String, String> getHeaders() throws AuthFailureError { 
        Map<String, String> headers = new HashMap<>(); 
        headers.put("X-OAPI-Key","TQEEGSk8OgWlhteL8S8siKao2q6LIGdq"); 
        headers.put("X-ISS-Key","2b2dd0d9dbb54ef79b7ee978532bc823"); 
        return headers; 
       } 
      }; 
      requestQueue.add(jsonArrayRequest); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

我的代碼同時適用於谷歌的官方凌空libray和mcxiaoke圖書館

如果你想使用谷歌的圖書館,你的Git克隆作爲谷歌文檔後,從\src\main\java\com複製的Android文件夾到你的項目爲下面的截圖中\app\src\main\java\com(你克隆排球項目):

enter image description here

build.gradle應包含以下

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    compile 'com.android.support:appcompat-v7:23.0.1' 
    compile 'com.google.code.gson:gson:2.3.1'  
} 

如果你的項目使用mcxiaoke的圖書館,在build.gradle將類似於以下(注意dependencies):

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 23 
    buildToolsVersion "23.0.0" 

    defaultConfig { 
     applicationId "com.example.samplevolley" 
     minSdkVersion 16 
     targetSdkVersion 23 
     versionCode 1 
     versionName "1.0" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    compile 'com.android.support:appcompat-v7:23.0.0' 
    compile 'com.mcxiaoke.volley:library:1.0.17' 
    compile 'com.google.code.gson:gson:2.3' 
} 

我建議您將創建2個新的示例項目,然後將使用Google的圖書館,另一個將使用mcxiaoke的圖書館。 UPDATE OF

END

 String url = "http://..."; 
     RequestQueue requestQueue = Volley.newRequestQueue(this); 
     final String jsonString = "[\n" + 
       " {\n" + 
       " \"value\": 1\n" + 
       " }\n" + 
       "]"; 
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       // do something... 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       // do something... 
      } 
     }) { 
      @Override 
      public byte[] getBody() { 
       try { 
        return jsonString.getBytes(PROTOCOL_CHARSET); 
       } catch (UnsupportedEncodingException uee) { 
        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", 
          jsonString, PROTOCOL_CHARSET); 
        return null; 
       } 
      } 
     }; 
     requestQueue.add(jsonObjectRequest); 

下面的截圖是領受的服務器端Web服務:

enter image description here

+0

我試過你的代碼,我得到一個與「PROTOCOL_CHARSET」相關的錯誤,它告訴我:'PROTOCOL_CHARSET'在com.android.volley.toolbox.JsonRequest – fujitsu4

+0

中有私人訪問我猜你的項目使用'compile'c​​om.mcxiaoke來使用排列庫。 volley:library:1.0.17'' in build.gradle file。我的項目使用谷歌的官方排球庫,可以用「utf-8」取代PROTOCOL_CHARSET – BNK

+0

我仍然收到錯誤:com.android.volley.ServerError。它'由於編程糟糕的排球庫?也許這將是一個解決方案採取谷歌之一? – fujitsu4