How to process response from HttpClient
Following code-snippet demonstrates way to handle Response.entity
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.testng.annotations.Test;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
public class Basic {
@Test
public void myThird() throws ClientProtocolException, IOException {
String url = “http://thecatapi.com/api/images/vote?api_key=xxxxx&sub_id=12345&image_id=bC24&score=10”;
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader(“User-Agent”, “Mozilla”);
HttpResponse response = client.execute(request);
System.out.println(“Response Code : ==>” + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = “”;
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result);
}
}
0 comments