Httpresponse java get body

How can I get an HTTP response body as a string?

I know there used to be a way to get it with Apache Commons as documented here: http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html . and an example here: http://www.kodejava.org/examples/416.html . but I believe this is deprecated. Is there any other way to make an http get request in Java and get the response body as a string and not a stream?

Since the question and all the answers seem to be about apache libraries, this should be tagged as such. I don’t see anything without using 3rdparty libs.

13 Answers 13

Here are two examples from my working project.

HttpResponse response = httpClient.execute(new HttpGet(URL)); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); 
HttpResponse response = httpClient.execute(new HttpGet(URL)); String responseString = new BasicResponseHandler().handleResponse(response); System.out.println(responseString); 

The only problem I faced with method 1 is, the entity object is consumed when you do response.getEntity() and it is now available as responseString . if you try to do a response.getEntity() again, it’ll return IllegalStateException .

Its so common to get the response content as string or byte array or something. Would be nice with an API directly on Entity to give you that. Having to look for this to find this util class.

Every library I can think of returns a stream. You could use IOUtils.toString() from Apache Commons IO to read an InputStream into a String in one method call. E.g.:

URL url = new URL("http://www.example.com/"); URLConnection con = url.openConnection(); InputStream in = con.getInputStream(); String encoding = con.getContentEncoding(); encoding = encoding == null ? "UTF-8" : encoding; String body = IOUtils.toString(in, encoding); System.out.println(body); 

Update: I changed the example above to use the content encoding from the response if available. Otherwise it’ll default to UTF-8 as a best guess, instead of using the local system default.

Читайте также:  Сортировка пузырьком java двумерный массив

this will corrupt text in many cases as the method uses the system default text encoding which varies based on OS and user settings.

@McDowell: oops thanks, I linked the javadoc for the method with encoding but I forgot to use it in the example. I added UTF-8 to the example for now, although technically should use the Content-Encoding header from the response if available.

Actually charset is specified in contentType like «charset=. «, but not in contentEncoding, which contains something like ‘gzip’

this function causes the input stream to be closed, is there a way @WhiteFang34 i can print my response and continue to use the http entity

Here’s an example from another simple project I was working on using the httpclient library from Apache:

String response = new String(); List nameValuePairs = new ArrayList(1); nameValuePairs.add(new BasicNameValuePair("j", request)); HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs); HttpPost httpPost = new HttpPost(mURI); httpPost.setEntity(requestEntity); HttpResponse httpResponse = mHttpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); if(responseEntity!=null)

just use EntityUtils to grab the response body as a String. very simple.

This is relatively simple in the specific case, but quite tricky in the general case.

HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://stackoverflow.com/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.getContentMimeType(entity)); System.out.println(EntityUtils.getContentCharSet(entity)); 

The answer depends on the Content-Type HTTP response header.

This header contains information about the payload and might define the encoding of textual data. Even if you assume text types, you may need to inspect the content itself in order to determine the correct character encoding. E.g. see the HTML 4 spec for details on how to do that for that particular format.

Once the encoding is known, an InputStreamReader can be used to decode the data.

This answer depends on the server doing the right thing — if you want to handle cases where the response headers don’t match the document, or the document declarations don’t match the encoding used, that’s another kettle of fish.

Источник

Чтение тела ответа HTTP как строки в Java

В этом руководстве мы рассмотрим несколько библиотек для чтения тела ответа HTTP в виде строки в Java. Начиная с первых версий Java предоставляет API HttpURLConnection . Он включает в себя только основные функции и известен тем, что не очень удобен для пользователя.

В JDK 11 компания Java представила новый и улучшенный API HttpClient для обработки связи по протоколу HTTP. Мы рассмотрим эти библиотеки и проверим альтернативы, такие как Apache HttpClient и Spring Rest Template .

2. HTTP-клиент ​

Как мы упоминали ранее, HttpClient был добавлен в Java 11. Он позволяет нам получать доступ к ресурсам по сети. Но, в отличие от HttpURLConnection , HttpClient поддерживает HTTP/1.1 и HTTP/2 . Более того, он предоставляет как синхронные, так и асинхронные типы запросов .

HttpClient предлагает современный API с большой гибкостью и мощными функциями. В основном этот API состоит из трех основных классов: HttpClient , HttpRequest и HttpResponse .

HttpResponse описывает результат вызова HttpRequest . HttpResponse не создается напрямую и становится доступным, когда тело полностью получено.

Чтобы прочитать тело ответа в виде строки, нам сначала нужно создать простые объекты клиента и запроса:

 HttpClient client = HttpClient.newHttpClient();   HttpRequest request = HttpRequest.newBuilder()   .uri(URI.create(DUMMY_URL))   .build(); 

Затем мы используем BodyHandlers и вызываем метод ofString() для возврата ответа:

 HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); 

3. HttpURL-соединение ​

HttpURLConnection — это легкий HTTP-клиент, используемый для доступа к ресурсам по протоколу HTTP или HTTPS и позволяющий нам создать InputStream . Получив InputStream, мы можем прочитать его как обычный локальный файл.

В Java основными классами, с которыми мы можем получить доступ к Интернету, являются класс java.net.URL и класс java.net.HttpURLConnection . Во-первых, мы будем использовать класс URL для указания на веб-ресурс. Затем мы можем получить к нему доступ с помощью класса HttpURLConnection .

Чтобы получить тело ответа из URL -адреса в виде строки , мы должны сначала создать HttpURLConnection , используя наш URL -адрес :

 HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection(); 

Новый URL(DUMMY_URL).openConnection() возвращает HttpURLConnection . Этот объект позволяет нам добавлять заголовки или проверять код ответа.

Далее, давайте получим InputStream из « объекта подключения :

 InputStream inputStream = connection.getInputStream(); 

4. HTTP-клиент Apache ​

В этом разделе мы увидим, как использовать Apache HttpClient для чтения тела ответа HTTP в виде строки.

Чтобы использовать эту библиотеку, нам нужно добавить ее зависимость в наш проект Maven:

 dependency>   groupId>org.apache.httpcomponentsgroupId>   artifactId>httpclientartifactId>   version>4.5.12version>   dependency> 

Мы можем получать и отправлять данные через класс CloseableHttpClient . Чтобы создать его экземпляр с конфигурацией по умолчанию, мы можем использовать HttpClients.createDefault() .

CloseableHttpClient предоставляет метод выполнения для отправки и получения данных. Этот метод использует параметр типа HttpUriRequest , который имеет множество подклассов, включая HttpGet и HttpPost .

Давайте сначала создадим объект HttpGet :

 HttpGet request = new HttpGet(DUMMY_URL); 

Во-вторых, давайте создадим клиент :

 CloseableHttpClient client = HttpClients.createDefault(); 

В- третьих, мы извлекаем объект ответа из результата метода execute :

 CloseableHttpResponse response = client.execute(request); 

Наконец, мы возвращаем тело ответа, преобразуя объект ответа в String :

 HttpEntity entity = response.getEntity();   String result = EntityUtils.toString(entity); 

5. Шаблон Spring Rest ​

В этом разделе мы увидим, как использовать Spring RestTemplate для чтения тела ответа HTTP в виде строки. Мы должны отметить, что RestTemplate теперь устарел : мы должны рассмотреть возможность использования Spring WebClient, как описано в следующей главе.

Класс RestTemplate — это важный инструмент, предоставляемый Spring, который предлагает простой шаблон для выполнения операций HTTP на стороне клиента над базовыми клиентскими библиотеками HTTP, такими как JDK HttpURLConnection , Apache HttpClient и другие.

RestTemplate предоставляет несколько полезных методов для создания HTTP-запросов и обработки ответов.

Мы можем использовать эту библиотеку, предварительно добавив некоторые зависимости в наш проект Maven:

 dependency>   groupId>org.springframework.bootgroupId>   artifactId>spring-boot-starter-webartifactId>   version>$ version>   dependency>   dependency>   groupId>org.springframework.bootgroupId>   artifactId>spring-boot-starter-testartifactId>   version>$ version>   scope>testscope>   dependency> 

Чтобы сделать веб-запрос и вернуть тело ответа в виде строки, давайте сначала создадим экземпляр RestTemplate :

 RestTemplate restTemplate = new RestTemplate(); 

Во- вторых, мы получаем объект ответа, вызывая метод getForObject() , передавая URL-адрес и желаемый тип ответа — в нашем примере мы будем использовать String.class :

 String response = restTemplate.getForObject(DUMMY_URL, String.class); 

6. Весенний веб-клиент​

Наконец, мы увидим, как использовать Spring WebClient, реактивное, неблокирующее решение, заменяющее Spring RestTemplate .

Мы можем использовать эту библиотеку, сначала добавив зависимость spring-boot-starter-webflux в наш проект Maven:

 dependency>   groupId>org.springframework.bootgroupId>   artifactId>spring-boot-starter-webfluxartifactId>   dependency> 

Самый простой способ выполнить HTTP-запрос Get — использовать метод create:

 WebClient webClient = WebClient.create(DUMMY_URL); 

Самый простой способ выполнить HTTP-запрос Get — вызвать методы получения и извлечения . Затем мы будем использовать метод bodyToMono с типом String.class , чтобы извлечь тело как один экземпляр String:

 MonoString> body = webClient.get().retrieve().bodyToMono(String.class); 

Наконец, давайте вызовем метод блока , чтобы указать веб-потоку ждать, пока весь основной поток не будет прочитан и скопирован в результат String:

7. Заключение​

В этой статье мы увидели, как использовать несколько библиотек для чтения тела ответа HTTP в виде строки .

Как обычно, полный код доступен на GitHub .

Источник

Parse http GET response body

I am connecting with a website and its api to retrieve data. My code below does that and gets the response body, but how do I parse that response body? Will I have to create my own function that will have to search for the terms that I want and then get the subcontents of each term? or is there already a library that I can use that can do that for me?

private class GetResultTask extends AsyncTask  < @Override protected String doInBackground(String. urls) < String response = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("https://api.bob.com/2.0/shelves/45?client_id=no&whitespace=1"); try < HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) < response += s; >> catch (Exception e) < e.printStackTrace(); >return response; > @Override protected void onPostExecute(String result) < apiStatus.setText(result); //setting the result in an EditText >> 

4 Answers 4

That data format is JSON (JavaScript Object Notation). So all you need is an android-compatible JSON parser, like GSON, and you’re good to go.

Ok, thank you, so that’s what JSON looks like. I’m just going to use the default org.json.JSONObject and write my own class

/That’s JSON, you can use a library like Jackson r Gson to deserialize it.

You can map your Java objects to the Json or deserialize it like a generic object.

Spring’s RestTemplate is so simple that it will automatically unmarshal (i.e. parse) the response body directly into Java objects that match the JSON format of the response:

First, define your Java classes to match the data format, using JAXB annotations if necessary. Here is a somewhat simplified model based on your response body:

@XmlRootElement class MyResponseData < long id; String url; String title; String created_by; int term_count; int created_date; int modified_date; boolean has_images; Listsubjects; Creator creator; List terms; > class Creator < String username; String account_type; String profile_image; >class Term

Then you just make the request with Spring’s RestTemplate

String url = "https://api.bob.com/2.0/shelves/45?client_id=no&whitespace=1"; RestTemplate template = new RestTemplate(); MyResponseData body = template.getForObject(url, MyResponseData.class); 

3 lines of code make the request and get the response body as a Java object. It’s doesn’t get much simpler.

Источник

Оцените статью