开发者

Using HttpURLConnection on Android

开发者 https://www.devze.com 2022-12-22 05:38 出处:网络
I am trying to connect a web server I have running in my android App however for some reason it\'s failing.

I am trying to connect a web server I have running in my android App however for some reason it's failing.

I can connect to the webpage normally and using my phone's browser, I can also use the below code to connect to google but for some reason my code will not connect to my web server. If I host the server on port 80 I get error code 503 every time, if I host it on 8080 (which is preferable) I get a timeout exception which is below.

03-05 20:12:22.432: WARN/System.err(29254): java.net.SocketException: The operation timed out
03-05 20:12:22.602: WARN/System.err(29254):     at org.apache.harmony.luni.platform.OSNetworkSystem.connectSocketImpl(Native Method)
03-05 20:12:22.602: WARN/System.err(29254):     at org.apache.harmony.luni.platform.OSNetworkSystem.connect(OSNetworkSystem.java:125)
03-05 20:12:22.602: WARN/System.err(29254):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:227)
03-05 20:12:22.612: WARN/System.err(29254):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:521)
03-05 20:12:22.612: WARN/System.err(29254):     at java.net.Socket.connect(Socket.java:1019)
03-05 20:12:22.612: WARN/System.err(29254):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:67)
03-05 20:12:22.612: WARN/System.err(29254):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager$ConnectionPool.getHttpConnection(HttpConnectionManager.java:151)
03-05 20:12:22.612: WARN/System.err(29254):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager.getConnection(HttpConnectionManager.java:73)
03-05 20:12:22.612: WARN/System.err(29254):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getHTTPConnection(HttpURLConnection.java:826)
03-05 20:12:22.612: WARN/System.err(29254):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:812)
03-05 20:12:22.612: WARN/System.err(29254):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getResponseCode(HttpURLConnection.java:1275)
03-05 20:12:22.612: WARN/System.err(29254):     at com.project.library.remailer.ServerSelect.downloadDirectory(ServerSelect.java:84)
03-05 20:12:22.622: WARN/System.err(29254):     at com.project.main.NewMessage$3$1$1.run(NewMessage.java:156)

The code is:

try {
    URL url = new URL(directoryLocation);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url
            .openConnection();

    // The line below is where the exception is called
    int response = httpURLConnection.getResponseCode();                 
    if (response == HttpURLConnection.HTTP_OK) {


        // Response successful
    InputStream inputStream = httpURLConnection.getInputStream();

    // Parse it line by line
    BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
    String temp;
    while ((temp = bufferedReader.readLine()) != null) {
        // Parsing of data here
    }
       } else {
            Log.e("SAMES", "INCORRECT RETURN CODE: " + response);
       }
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

When I try the code in the link suggested by CommonsWare for port 8080 I get the same error as before, the timeout exception. For port 80 I get the following exception, both of these errors occur on the url.openStream().

Port 80 exception:

03-06 11:53:53.296: WARN/System.err(639): java.io.FileNotFoundException: http://64.197.194.165:80/path
03-06 11:53:53.376: WARN/System.err(639):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1064)
03-06 11:53:53.376: WARN/System.err(639):     at java.net.URL.openStream(URL.java:674)
03-06 11:53:53.376: WARN/System.err(639):     at com.proje开发者_运维知识库ct.library.remailer.ServerSelect.downloadDirectory(ServerSelect.java:118)
03-06 11:53:53.376: WARN/System.err(639):     at com.project.main.NewMessage$3$1$1.run(NewMessage.java:156)

I also tried using the following code:

HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(directoryLocation);
        try
        {
            HttpResponse response = client.execute(request);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line;
            while((line = reader.readLine()) != null) {
                Log.e("SAMES", line);
        }

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

However that has resulted in the same timeout error for port 8080, which occurs when client.execute(response) is called.

For port 80 I get a webpage which says that it couldn't connect, which alot of HTML editing, however the main thing it says on the page is:

03-06 13:10:23.576: ERROR/SAMES(1267): The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests. You may wish to try again at a later time.


Various notes:

  • You don't indicate where the timeout occurred.
  • You might try this example, which uses URL differently than you are.
  • Your error code 503 on port 80 should result in some error information on your server that might be useful.
  • Are there any proxy servers or other things between your phone and the Web server?
  • Have you tried with both WiFi and 3G?
  • You might try switching to HttpClient and see if you get better results or perhaps a better error message.


Your issue is too complex (in my opinion) to address it fully, so I'd like to share my findings on a problem I've been having recently, which caused exactly what you described in your comment:

// The line below is where the exception is called
int response = httpURLConnection.getResponseCode();

That same piece of code caused IOException in one of my classes - every time, on every valid URL, so it was clear the problem was in the code - which looked the same as yours - simple, no headers set, nothing above tutorial-like examples. I then noticed that every example I've seen was not even calling URLConnection.connect() method - so I thought: when does the actual connection occur? What does standard HttpURLConnection use pattern look like?

Unfortunately, the documentation is scarce on that topic. So I've done some googling and found this blog post: HttpURLConnection's Dark Secrets - by Tim Bray which was invaluable in writing more complex HttpURLConnection use-ceses. It also provided an answer to my problem - let me quote relevant lines:

// this opens a connection, then sends GET & headers 
in = conn.getInputStream(); 

// can't get status before getInputStream.  If you try, you'll
//  get a nasty exception.
http_status = conn.getResponseCode();

// better check it first
if (http_status / 100 != 2) {
   // redirects, server errors, lions and tigers and bears! Oh my!
}

See the 1st and 2nd comment? Well, that makes a lot of sense when you know that actual network connection is initiated by HttpURLConnection.getInputStream() (HttpURLConnection.getOutputStream() if you're sending any content to the server). Placing invocation of getResponseCode() after getInputStream() fixed my problem.


What happens if you try calling httpURLConnection.connect() after calling url.openConnection()?


Only an app with root permissions can open ports below 1024 - that's the issue with port 80.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号