A normal Java get request


In Python there is a special function for get-запросов, with which you can quickly get the status and content:

response = requests.get(url)
print response.status_code
print response.content

When I try to Google get запрос в Java, I get different instructions on how to create a socket, then establish a connection, and so on. Aren't there any simple ways in Java without inventing your own bikes ?

Author: faoxis, 2016-10-18

2 answers

Get-the request can be made, for example, as follows:

String url = "http://www.google.com/";

URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

connection.setRequestMethod("GET");

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

System.out.println(response.toString());
 7
Author: post_zeew, 2016-10-18 14:18:42

You can use the http-request built on the apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createGet(uri, String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
  ResponseHandler<String> response = httpRequest.execute(someParamsYouWant);
  System.out.println(response.getStatusCode());
  System.out.println(response.get()); //retuns response body
}
 3
Author: Beno Arakelyan, 2017-09-17 12:30:38