4

I'm trying to send a get request in order to get a website content. When I'm using Postman it takes about 70-100 ms, but when I use the following code:

String getUrl = "someUrl";

URL obj = new URL(getUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");

//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

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

response.toString();

it takes about 3-4 seconds.

Any idea how to get my code work as fast as Postman?

Thanks.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
Dan
  • 71
  • 7

2 Answers2

0

Try to find a workaround for the while loop. Maybe that is your bottleneck. What are you even getting from your URL? Json object or something else?

cotnic
  • 158
  • 2
  • 11
0

Try http-request built on apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createGet(someUri, String.class)
    .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
    .addDefaultHeader("User-Agent", "Mozilla/5.0")
    .build();

public void send(){
   String response = httpRequest.execute().get();
}

I higly recomend read documentation before use.

Beno
  • 945
  • 11
  • 22