2016-12-31 120 views
0

我正在使用Android註釋向服務器發出請求。我創建了一個基於回答以下攔截此questionAndroid註釋記錄攔截器輸入錯誤末端

public class LoggingInterceptor implements ClientHttpRequestInterceptor { 

@Override 
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { 
    ClientHttpResponse response = execution.execute(request, body); 

    //It works after removing these two lines 
    String responseString = stringOf(response.getBody()); 
    Log.d("RESPONSE", responseString); 

    return response; 
} 

public static String stringOf(InputStream inputStream) { 
    inputStream.mark(Integer.MAX_VALUE); 
    BufferedReader r = new BufferedReader(new InputStreamReader(inputStream)); 
    StringBuilder strBuilder = new StringBuilder(); 
    String line; 
    try { 
     while ((line = r.readLine()) != null) 
      strBuilder.append(line); 
    } catch (IOException ignored) {} 
    try { 
     inputStream.reset(); 
    } catch (IOException ignored) {} 
    return strBuilder.toString(); 
} 
} 

然而,這產生了以下異常:org.springframework.http.converter.HttpMessageNotReadableException:無法讀取JSON:無內容由於地圖結束輸入

當我刪除自攔截以下行:

String responseString = stringOf(response.getBody()); 
Log.d("RESPONSE", responseString); 

,一切工作正常。

這裏是我的RESTClient實現接口:

@Rest(rootUrl= "http://107.206.158.62:1337/api/", converters={MappingJackson2HttpMessageConverter.class}, interceptors = { LoggingInterceptor.class }) 
public interface IRestClient { 

    @Post("users/register/") 
    @Accept(MediaType.APPLICATION_JSON) 
    User register(@Body User user); 

} 

用戶模型:在我的活動

public class User implements Serializable { 

    String first_name; 

    String last_name; 

    String email; 

    String password; 

    public User(){} 

    public User(String first_name, String last_name, String email, String password) { 
     this.first_name = first_name; 
     this.last_name = last_name; 
     this.email = email; 
     this.password = password; 
    } 

    //Getters and Setters 
} 

RESTClient實現通話

@Click(R.id.bRegister) 
@Background 
void createAccount() { 
    User u = restClient.register(new User("Test Fname", "Test Lname", "[email protected]", "testpass")); 
    Log.d("User last name", u.getLast_name()); 
} 

服務器產生以下JSON:

{"first_name":"Test Fname","last_name":"Test Lname","email":"[email protected]"} 

我想能夠登錄的每個響應的主體,然後返回響應對象。但是看起來,首先從響應中讀取InputStream會導致一些問題。

Log.d("RESPONSE", responseString); 

正在產生正確的服務器響應,但後來我碰到了上面的異常時英寸

MappingJackson2HttpMessageConverter踢任何幫助將不勝感激!新年快樂! :)

回答

1

我想這是因爲當你閱讀響應你消耗它,然後它是空的。攔截器在內容解析之前就起作用,所以你消耗了你的響應來記錄它,然後解析器發現它是空的。

測井響應簡單地閱讀它的內容是不是要做到這一點的最好辦法。我不知道什麼是最好的技術,但我一直在評論響應記錄,然後當我有一個問題,我與調試停止線進入攔截方法和日誌手錶面板的要求,寫東西像

Log.d("RESPONSE", stringOf(response.getBody())) 

然後您可以將記錄的數據讀入Android監視器面板。 顯然,這反應現在是空的,所以它不會被解析和處理,但是當你需要,你可以登錄你的迴應不重建項目

+0

謝謝!這幫助了我 – eHero