如何通过改造从服务器接收消息?

时间:2014-07-25 13:14:52

标签: java android rest retrofit

服务器向我发送失败消息: Timer is already running

当我发送请求时,我会在logcat Intellij:

中得到答案
07-25 16:13:42.924    4321-4426/com.winify.happy_hours D/Retrofit﹕ ---> HTTP POST http://192.168.3.93:9000/start

07-25 16:13:42.929    4321-4426/com.winify.happy_hours D/Retrofit﹕ Content-Type: application/json; charset=UTF-8

07-25 16:13:42.929    4321-4426/com.winify.happy_hours D/Retrofit﹕ Content-Length: 38

07-25 16:13:42.930    4321-4426/com.winify.happy_hours D/Retrofit﹕ {"token":"sbkq109up7cjc2sl27nhdr9r31"}

07-25 16:13:42.930    4321-4426/com.winify.happy_hours D/Retrofit﹕ ---> END HTTP (38-byte body)

07-25 16:13:53.586    4321-4426/com.winify.happy_hours D/Retrofit﹕ <--- HTTP 400 http://192.168.3.93:9000/start (10655ms)

07-25 16:13:53.586    4321-4426/com.winify.happy_hours D/Retrofit﹕ : HTTP/1.1 400 Bad Request

07-25 16:13:53.587    4321-4426/com.winify.happy_hours D/Retrofit﹕ Content-Length: 24.

07-25 16:13:53.589    4321-4426/com.winify.happy_hours D/Retrofit﹕ Content-Type: text/plain; charset=utf-8

07-25 16:13:53.589    4321-4426/com.winify.happy_hours D/Retrofit﹕ X-Android-Received-Millis: 1406294033585

07-25 16:13:53.589    4321-4426/com.winify.happy_hours D/Retrofit﹕ X-Android-Sent-Millis: 1406294022933

07-25 16:13:53.590    4321-4426/com.winify.happy_hours D/Retrofit﹕ Timer is already running

07-25 16:13:53.591    4321-4426/com.winify.happy_hours D/Retrofit﹕ <--- END HTTP (24-byte body)

如何在改进时出现错误消息: Timer is already running

1 个答案:

答案 0 :(得分:1)

错误消息是响应正文的一部分。这是一种非常简单的方法,可以访问它。

// Util method to make it easier to transform a stream into a byte array
static byte[] streamToBytes(InputStream stream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (stream != null) {
        byte[] buf = new byte[1024];
        int r;
        while ((r = stream.read(buf)) != -1) {
            baos.write(buf, 0, r);
        }
    }
    return baos.toByteArray();
}

代码中的某处你会有类似的东西

try {
    yourRestApi.getSomeDataRestCall();
} catch (RetrofitError e) {
    if (e.getResponse != null) {
        TypedInput body = e.getResponse().getBody();
        byte[] bytes = streamToBytes(body.in());
        String charset = MimeUtil.parseCharset(body.mimeType());
        // This will be your error message
        String errorMsg = new String(bytes, charset);
    }
}

如果您对更完整的解决方案感兴趣,那么有一个非常好的要点,其中包含更多详细信息here