2017-12-14 29 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