James Robert Singleton James Robert Singleton - 3 months ago 22
Android Question

Accessing OKHttp Response Body

So I need to figure out how to access the value I get from my first response in my second. I would think that I could just store it to a a variable and access it in another request. However, that does not seem to be the case.

Here is the bit that is giving me issues. So my first request is getting me a token and then I need to use that which is stored in commatoken in my second request.

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
Request request = new Request.Builder()
.url(API_URL + authPreferences.getToken())
.build();

client.newCall(request).enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}


public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}

System.out.println(response.body().string());
String commatoken = response.body().string();
}
});

Request dataRequest = new Request.Builder()
.header("Authorization", "jwt"+commatoken)
.url(ChffrMe_URL).build();

client.newCall(dataRequest).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}

System.out.println(response.body().string());

}
});
}

Answer

I think we can call response.body().string() only once .... so save that data to a string variable first .. and access it wherever you need it.

String response_data;
..............
response_data = response.body().string();

You are calling response.body().string() twice ...

More info http://stackoverflow.com/a/27922818/3552066

Comments