2017-12-14 42 views
2

これは私のJSON体である:Okhttpでオブジェクトを渡してPOSTリクエストを作成するには?

Username username = new Username("IN" , "9620494812"); 

JSONObject postData = new JSONObject(); 

try { 
    postData.put("username" , username); 
    postData.put("password" , "119209"); 

} catch (JSONException e) { 
    e.printStackTrace(); 
} 

RequestBody body = RequestBody.create(MEDIA_TYPE , postData.toString()); 

Request request = new Request.Builder().url("https://www.gruppie.in/api/v1/login") 
     .method("POST" , body).build(); 

私は要求を確認しているが、私はまだ

としてエラーが発生します:次のように私は OkhttpでPOSTリクエストを作成しようとしている

{ 
    "username": { 
     "country": "IN", 
     "number": "9620494812" 
    }, 
    "password": "119209" 
} 

応答は次のとおりです。

{"status":401,"type":"about:blank","title":"Unauthorized"} 

何私はここで間違っていますか?

+0

https://stackoverflow.com/questions/34179922/okhttp-post-body-as-json答えを –

答えて

4

JSONごとに、JSONリクエストを送信する必要があります。私は何の間違いで作った... ...それは正しく働いているこの

JSONObject postData = new JSONObject(); 
    JSONObject userJson=new JSONObject(); 
    try { 
     userJson.put("country","IN"); 
     userJson.put("number","9620494812"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    try { 
     postData.put("username" , userJson); 
     postData.put("password" , "119209"); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
+0

感謝を試してみてください私のコード? – Saathwik

関連する問題