我正在使用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