2014-12-10 1 views
4

최신 Volley 라이브러리를 사용 중이며 API에서 응답없이 본문이없는 204 개를 반환 할 때 문제가 있습니다.Android Volley 라이브러리가 204 및 비어있는 본문 응답과 함께 작동하지 않습니다.

// Some responses such as 204s do not have content. We must check. 
if (httpResponse.getEntity() != null) { 
    responseContents = entityToBytes(httpResponse.getEntity()); 
} else { 
    // Add 0 byte response as a way of honestly representing a 
    // no-content request. 
    responseContents = new byte[0]; 
} 

getEntity의 결과가 나에게 널 결코 있지만 비어 있습니다 : 예상대로 BasicNetwork.java에 다음 코드가 작동하지 않는 것 같습니다. 나는 API가 컬 (curl)과 우편 배달부 (postman)를 체크하여 아무것도 반환하지 않는다는 것을 확신했다. 다른 누구도 그런 문제가 있습니까?

는 지금은 그냥 변경했습니다 그 경우에 : 나는 근본 원인을 해결하지 알고,하지만 난 더 깊이 잠수하기 전에 분명 아무것도없는 아니에요 있는지 확인하려면

if (statusCode != HttpStatus.SC_NO_CONTENT && httpResponse.getEntity() != null) 

이 문제에.

감사합니다.

편집 : 죄송합니다. 실제 문제는 검색 할 본문이 없으므로 이상한 메서드 인 entityToBytes에서 시간 초과 예외가 발생했다는 것을 잊어 버렸습니다.

또한 실제 사용할 수없는 웹 서비스 API를 사용하고 있지 않습니다. 대신 나는 양봉장에있는 조롱당한 웹 서비스에 연결하고 있습니다.하지만 양봉장이 문제가 될 수는 없습니다.

+0

는'entityToBytes'이가 늦게 죄송합니다 아무 내용도 – njzk2

+0

가없는 경우 길이가 0 바이트 []를 반환 나타납니다,하지만 난 같은 문제를했고 진짜 문제는 HttpStack 내 구현했다. 'getEntity()'가 null 인 경우 Apache의 새로운 라이브러리를 사용하고 새 객체와 말한 객체 사이를 변환합니다. 빈 실체를 반환했습니다. 당신이 발행하는 것이 유사 할 수도 있습니다. – Ali

+0

응답이'getEntity'가'null'을 반환하면 volley가 그대로 작동해야한다면'HttpStack' 구현의'performRequest' 메소드를보십시오. 나처럼 옛날 아파치 라이브러리와 새로운 아파치 라이브러리간에 변환을하거나 다른 처리를하고 있다면 빈 개체를 추가 할 수있다. – Ali

답변

5

이것은 해결책에 대한 자세한 설명보다 적습니다. 먼저, API에서 204 개의 응답을 사용하고 똑같은 문제가 발생했습니다. 나는 그것을 해결하기 위해 BasicNetwork.java의 코드를 사용 - 나는 또한 내가 표준 JsonObjectRequest 요청을 사용하는 경우 신체가 null이기 때문에 다음 Response.ErrorListener가 트리거 될 수 있음을 알게되었다 무엇 라인 if (statusCode != HttpStatus.SC_NO_CONTENT && httpResponse.getEntity() != null)

합니다.

null 또는 공백 본문의 경우 성공 응답을 제공하는 JsonObjectRequestWithNull을 새로 만들었습니다. 코드 :

public class JsonObjectRequestWithNull extends JsonRequest<JSONObject> { 

public JsonObjectRequestWithNull(int method, String url, JSONObject jsonRequest, 
         Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { 
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, 
      errorListener); 
} 

public JsonObjectRequestWithNull(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, 
         Response.ErrorListener errorListener) { 
    this(jsonRequest == null ? Request.Method.GET : Request.Method.POST, url, jsonRequest, 
      listener, errorListener); 
} 

@Override 
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { 
    try { 
     String jsonString = new String(response.data, 
       HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); 
     //Allow null 
     if (jsonString == null || jsonString.length() == 0) { 
      return Response.success(null, HttpHeaderParser.parseCacheHeaders(response)); 
     } 
     return Response.success(new JSONObject(jsonString), 
       HttpHeaderParser.parseCacheHeaders(response)); 
    } catch (UnsupportedEncodingException e) { 
     return Response.error(new ParseError(e)); 
    } catch (JSONException je) { 
     return Response.error(new ParseError(je)); 
    } 
} 

}

관련 비트는 다음과 같습니다

 //Allow null 
     if (jsonString == null || jsonString.length() == 0) { 
      return Response.success(null, HttpHeaderParser.parseCacheHeaders(response)); 
     } 

누군가에게 도움이 바랍니다.

0

사용자 정의 HttpStack 또는 수정 (gradle dependency : compile 'com.mcxiaoke.volley : library : 1.0.15')없이 표준 Volley 라이브러리를 사용한다면 변경 사항 만 있으면됩니다. include 클래스는 요청 클래스의 parseNetworkResponse 메서드에 있습니다 (이 코드는 Gson을 사용하여 Json으로 변환한다고 가정합니다.이 클래스는 내가 작성한 사용자 정의 GsonRequest 클래스에서 가져옵니다).

@Override 
protected Response<T> parseNetworkResponse(NetworkResponse response) { 
    try { 
     final String json = new String(
       response.data, HttpHeaderParser.parseCharset(response.headers)); 

     if (TextUtils.isEmpty(json)) { 
      return Response.success(null, HttpHeaderParser.parseCacheHeaders(response)); 
     } 

     return Response.success(gson.fromJson(json, clazz), null); 
    } catch (UnsupportedEncodingException e) { 
     return Response.error(new ParseError(e)); 
    } catch (JsonSyntaxException e) { 
     return Response.error(new ParseError(e)); 
    } 
} 
관련 문제