0

Im my Android app I have a client which has to perform several HTTP requests per second to a server.

I achieve this as follows:

        public class myclient implements Runnable {

           private HttpClient httpClient = null;
           private HttpParams params = null;
           private HttpGet httpRequest;

           myclient () {
                httpClient = new DefaultHttpClient();
                params = httpClient.getParams();
                httpRequest = new HttpGet(request);

                HttpConnectionParams.setConnectionTimeout(params, 60000);
                HttpConnectionParams.setSoTimeout(params, 60000);
                ...
           }

           @Override
           public void run() {

                HttpResponse response = httpClient.execute(httpRequest);
                HttpEntity entity = response.getEntity();

                BufferedHttpEntity bufferedHttpEntity = new  BufferedHttpEntity(entity);

                InStream = bufferedHttpEntity.getContent();
           ...
           }
    }

Now the problem: while the destination port of each request is the port 80, the local port changes at each request. This causes some trouble with firewalls. Is there some way to keep the local port constant? I solved this porblem in a .NET application setting the local port to a fixed value. But here it seems impossible. Moreover I suppose that the change in local port means a new TCP connection: why the connection is not preserved?

peregrinus
  • 147
  • 1
  • 12
  • That each requests open a new TCP connection means either the server does not allow connection reusing (unlikely) or that you are using the apache http library wrong so that connection can't be reused. Your requests should like like here: https://stackoverflow.com/a/31659073/150978 – Robert Mar 09 '18 at 11:40
  • `means a new TCP connection: why the connection is not preserved?` Http is a connectionless protocol. – greenapps Mar 09 '18 at 11:42
  • @greenapps Yes, you are right but even if the Http is connectionless you should be able to exploit the same TCP connection since TCP is connection oriented. The problem has been also addressed here: https://mttkay.github.io/blog/2013/03/02/herding-http-requests-or-why-your-keep-alive-connection-may-be-dead/ I implemented my requests both with HttpClient and HttpUrlConnection classes but in both cases I am not able to keep keep connection alive for different Http requests. – peregrinus Mar 09 '18 at 17:27
  • Do you have access to the underlying socket? – greenapps Mar 10 '18 at 09:08
  • I am using Android API. As far as I am concerned I can perform http requests only with the HttpClient and HttpUrlConnection classes. My aim si to keep constant the local port and I can get this a) by keeping the connection open (thi depends also on the server), b) by setting the local port (preferable). Maybe the only way is to use JNI. – peregrinus Mar 12 '18 at 08:55

0 Answers0