2014-11-02 4 views
8

저는 일반적으로 발리와 안드로이드를 처음 접했습니다. 아래 코드 발췌 문장 (안드로이드 발리를 사용하여) 나는 실행하려고하지만 서버가 400을 반환합니다. 다른 REST 클라이언트를 사용하면 완벽하게 작동합니다. PUT 메소드를 사용하여 서버에 요청합니다.Android 발리 PUT 요청

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); 
    sendRequest(); 
} 

private void sendRequest() { 
    RequestQueue queue = Volley.newRequestQueue(this); 

    final JSONObject jsonObject = new JSONObject(); 
    try { 
     jsonObject.put("password", "ttttt"); 
     jsonObject.put("username", "tester3"); 
     jsonObject.put("token", "blah"); 
    } catch (JSONException e) { 
     // handle exception 
    } 


    JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, url, jsonObject, 
      new Response.Listener<JSONObject>() 
      { 
       @Override 
       public void onResponse(JSONObject response) { 
        // response 
        Log.d("Response", response.toString()); 
       } 
      }, 
      new Response.ErrorListener() 
      { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        // error 
        Log.d("Error.Response", error.toString()); 
       } 
      } 
    ) { 

     @Override 
     public Map<String, String> getHeaders() 
     { 
      Map<String, String> headers = new HashMap<String, String>(); 
      headers.put("Content-Type", "application/json"); 
      headers.put("Accept", "application/json"); 
      return headers; 
     } 

     @Override 
     public byte[] getBody() { 

      try { 
       Log.i("json", jsonObject.toString()); 
       return jsonObject.toString().getBytes("UTF-8"); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 
    }; 

    queue.add(putRequest); 
} 

이 코드를 실행할 때 항상 400 개의 잘못된 요청이 다시 발생하고 이유를 파악할 수 없습니다. Postman과 같은 다른 클라이언트를 사용하면 예상대로 작동합니다. 다음은 우편 배달부 요청은 다음과 같습니다

원시 요청 :
{ "토큰": "ㅋ", "비밀번호": "은 ttttt" "사용자 이름": "tester3" }

Headers: Content-Type: application/json 

요청에 아무 것도 보이지 않습니다. 누군가 내가 잘못하고있는 것을 지적 할 수 있기를 바랍니다.

+0

해결책을 찾았습니까? 나는 또한 같은 상황에 처해있다. – RmK

+1

나는 두려워하지 않고 시간을 다 써 버렸고 개조를 사용했다. – WolfBane

+1

심지어 나는 시간이 없어. 체크 아웃을 갱신했지만 단기간에 파악할 수는 없습니다. 그러나 귀하의 질문은 문제를 해결하는 데 도움이되었습니다. 012erspput (Accept "Accept", "application/json") 헤더를 추가했습니다. 감사합니다. – RmK

답변

-4

나는 이것을하는 방법을 찾기 위해 많은 시간을 보냈습니다. 무엇 나를 위해 일한도 getBodyContentType을 (오버라이드 (override)하기 위해 더 나은 작동하지 않습니다 헤더 "의 Content-Type", 대해 getHeaders에서 "응용 프로그램/JSON을"()를 추가, 때로는

Request.Method.POST 
+0

그러나 이것은 질문에 관한 것이다. – Niroshan

+0

너는 천재 야. –

4

Request.Method.PUT 

을 변경했다) 여기에 헤더를 반환합니다. POST를 사용하는 동안

@Override 
    public String getBodyContentType() { 
     return "application/json"; 
    } 

이 그래서 따라와

, 또한

public Map<String, String> getHeaders() 
    { 
     Map<String, String> headers = new HashMap<String, String>(); 
     headers.put("Content-Type", "application/json"); 
     return headers; 
    } 

추가는, 나를 위해 일했다.

0

그냥이처럼 StringRequest으로 시도 :

StringRequest putRequest = new StringRequest(Request.Method.PUT, url, 
     new Response.Listener<String>() 
     { 
@Override 
public void onResponse(String response) { 
     // response 
     Log.d("Response", response.toString()); 
     } 
     }, 
     new Response.ErrorListener() 
     { 
@Override 
public void onErrorResponse(VolleyError error) { 
     // error 
     Log.d("Error.Response", error.toString()); 
     } 
     } 
     ) { 

@Override 
public Map<String, String> getHeaders() 
     { 
     Map<String, String> headers = new HashMap<String, String>(); 
     headers.put("Content-Type", "application/json"); 
     //or try with this: 
     //headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); 
     return headers; 
     } 
@Override 
protected Map<String, String> getParams() { 
     Map<String, String> params = new HashMap<String, String>(); 
     params.put("password", "ttttt"); 
     params.put("username", "tester3"); 
     params.put("token", "blah"); 
     return params; 
     } 
     }; 

     queue.add(putRequest); 
     } 
1

JsonObjectRequest은 기본적으로 Content-Type: application/json; charset=utf-8을 추가합니다. headers.put("Content-Type", "application/json");Content-Type을 추가하고 일부 응용 프로그램은 복수 Content-Type 정의와 함께 작동하지 않습니다. headers.put("Content-Type", "application/json");을 삭제해야합니다.

+0

내 문제를 해결했다. 때로는 그런 기본적인 것들을 잊어 버리는 경우도 있습니다. – Martin

0
@Override 
public String getBodyContentType() { 
    return "application/json"; 
} 

이것은 PUT 요청을 사용하여 나를 위해 일했습니다.