Android URLConnection does only work in wifi, not

2019-07-24 23:26发布

问题:

I have written an app which uses an URLConnection to get a .html file. Everything works fine over wifi. But over 3g the file is not returned correctly. When i try to access the website via the browser it works fine. Anyone has a suggestion?

Update: Here is my code:

URL downloadUrl;
URLConnection downloadConnection;
InputStream inputStream;
byte[] inputBytes;
String[] output;
private void downloadSource(String pUrl)
{

    try
    {
        downloadUrl = new URL(pUrl);

        downloadConnection = downloadUrl.openConnection();
        downloadConnection.setConnectTimeout(10000);
        downloadConnection.setReadTimeout(10000);


        inputStream = downloadConnection.getInputStream();
        ByteArrayOutputStream result = new ByteArrayOutputStream();

        inputBytes = new byte[10000];
        int i;
        int i1 = 0;
        while ((i = inputStream.read(inputBytes)) > 0)
        {
            result.write(inputBytes, 0, i);
            result.flush();
            i1 += i;
        }
        result.flush();
        result.close();
        output = result.toString().split("\n"); 

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


}

回答1:

Maybe it's a little bit late for answer but I had the same problem, with Wifi the html downloaded had different spaces than the one downloaded with 3G.

I solved it deleting the User-Agent in the connection:

URLConnection conn = url.openConnection();  
conn.setRequestProperty("User-Agent","");

I hope it helps someone!