How to parse XML return from OkHttp?

This is my OkHttp message form customization method using the OkHttp Async Get method

public Call postGetCountries(Callback callback) {
    RequestBody body = new FormEncodingBuilder()
        .add("op", "op")
        .build();

    Log.d(TAG_PARAMS, "op=sgetcountrylist, app_type=1");

    Request request = new Request.Builder()
        .url(GATEWAY_URL)
        .post(body)
        .build();

    Call call = CLIENT.newCall(request);
    call.enqueue(callback);

    return call;
}

This is my custom callback.

private class GetCountriesCallback implements Callback {
    @Override
    public void onFailure(Request request, IOException e) {
        Log.e("OkHttp", e.getMessage());
    }

    @Override
    public void onResponse(Response response) throws IOException {
        Log.d("PASSED", "PASS");
        Log.d(Connection.TAG_RETURN, response.body().string());

        try {
            InputStream is = response.body().byteStream();
            List test = connectionParser.parse(is, "op");

        } catch (XmlPullParserException e) {
            Log.e("PARSE ERROR", e.getMessage());
        }
    }
}

This is my instance of the parse method.

public List parse(InputStream in, String op) throws XmlPullParserException, IOException {
    try {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        parser.nextTag();
        return readFeed(parser, op);
    } finally {
        in.close();
    }
}

I am currently testing whether it works, unfortunately I am getting a refund

10-06 11:54:42.492 6336-6892/ D/PASSED: PASS
10-06 11:54:42.692 6336-6892/ E/PARSE ERROR: Invalid stream or encoding: java.io.IOException: closed (position:START_DOCUMENT null@1:1) caused by: java.io.IOException: closed

This is what I use in my onCreate for activity to start the whole process:

private Connection connect = Connection.getInstance();
connect.postGetCountries(new GetCountriesCallback());

I do not understand why InputStream is closing.

+4
source share
1 answer

Two things can happen. First, you can only read the body once. If you want to read it more than once, you need to save the result somewhere. You read the body twice, once here -

Log.d(Connection.TAG_RETURN, response.body().string());

and then here -

InputStream is = response.body().byteStream();
List test = connectionParser.parse(is, "op");

. - .

, , , - onResponse , HTTP . Response code() isSuccesful(), , .

+5

Source: https://habr.com/ru/post/1610351/


All Articles