Android URLConnection does only work in wifi, not with 3g

情到浓时终转凉″ 提交于 2019-12-11 08:38:22

问题


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!



来源:https://stackoverflow.com/questions/8104831/android-urlconnection-does-only-work-in-wifi-not-with-3g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!