HttpURLConnection - Lots of requests
Asked Answered
E

0

1

I have written a service which is used to register some data. That service can be called thousands of times. The parameters are passed via the URL itself. The client part of it looks something like this:

private String getNodeInfoFromGPSForSpecificSubscriber( int subscriberId ) throws Exception {
        String requestURLToNode = "http://" + GPSConstants.GPS_IP + ":" + GPSConstants.PORT_NUMBER + APIs.FetchASpeecificNodeAPI.FETCH_A_SPECIFIC_NODE + "?" + APIs.FetchASpeecificNodeAPI.SUBSCRIBER_ID + "=" + subscriberId;
        URL url = new URL( requestURLToNode );
        HttpURLConnection conn = ( HttpURLConnection ) url.openConnection();
        conn.setRequestMethod( "GET" );
        conn.setRequestProperty( "Accept", "application/xml" );
        conn.setDoOutput( true );
        InputStream inputStream = conn.getInputStream();


        BufferedReader in = new BufferedReader( new InputStreamReader( inputStream ) );
        String responseAsString = in.readLine();
        in.close();

        conn.disconnect();
        System.out.println( ++i );

        return responseAsString;
    }

But here, every time a connection gets opened, and thus speed am getting is only around 1 record per second. I know I need not open a connection everytime, but not able to figure out how. Kindly help.

Enwreathe answered 11/4, 2014 at 16:21 Comment(6)
Sorry, I don't understand your last sentence. What exactly do you want to know?Remington
If I have to call my server multiple times, how can I do it? The above code throws 14/04/11 22:47:25 ERROR client.RegisterNewCell: java.net.SocketException: No buffer space available (maximum connections reached?): connect after some runs.Enwreathe
If I remove in.close() in the above code, it runs faster but then stops throwing that exception.Enwreathe
Are you sure you're not swallowing exceptions? in.close() and conn.disconnect() are only called in "happy-path". Maybe you need more robust exception handling!? Try a tested library like DavidWebb or one of the listed alternatives.Remington
The exception is occurring when its opening too many tcp connections. I dont have any other exceptions in the code. If I use in.close() the speeds am getting is only a request per second.Enwreathe
I have used the same code except: conn.setRequestProperty( "Accept", "application/xml" ); conn.setDoOutput( true ); and on apache log i have found that with get parameter the is only 1 request where without get parameter there are too many ... ?? don't know why ?Heredity

© 2022 - 2024 — McMap. All rights reserved.