我正在使用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踢任何幫助將不勝感激!新年快樂! :)
謝謝!這幫助了我 – eHero