www.text not showing complete data in android

2020-02-06 16:56发布

问题:

I'm using the following code to get the text from a web page:

    private IEnumerator FetchText() {
        WWW www = new WWW(URL);

        yield return www;

        if(www.error == null) {
            myText.text = www.text.Length.ToString();
        }
        ...
    }

When I run this in Unity, I get 185616 characters long string. But when I run this in android device, I get only 47133 characters. Is it because that web page behaves differently in Windows and Android? If yes, how can I fetch the same content from android as I'd be getting from desktop PC.

Thanks.

回答1:

Implementation of tier1's answer.

POST Request:

private IEnumerator FetchText()
{
    string URL = "www.yahoo.com";
    string userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";

    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("User-Agent", userAgent);
    string postData = "test";
    string data = "data=" + postData;

    WWW www = new WWW(URL, Encoding.UTF8.GetBytes(data), headers);
    yield return www;


    if (string.IsNullOrEmpty(www.error))
    {
        //myText.text = www.text.Length.ToString();
        Debug.Log("Got: " + www.text);
    }
    else
    {
        Debug.Log("Error: " + www.error);
    }
}

GET Request:

Setting the WWW byte[] postData parameter to null will make it a GET request.

private IEnumerator FetchText()
{

    string userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
    string URL = "www.yahoo.com";

    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("User-Agent", userAgent);

    WWW www = new WWW(URL, null, headers);
    yield return www;


    if (string.IsNullOrEmpty(www.error))
    {
        //myText.text = www.text.Length.ToString();
        Debug.Log("Got: " + www.text);
    }
    else
    {
        Debug.Log("Error: " + www.error);
    }
}

According your original code, you need the GET request method. This will masquerade as request from a Chrome browser. You can get your User-Agent from here.



回答2:

It's possible that the URL you are trying to fetch is detecting your user agent and sending you to some kind of mobile site with a smaller response body.

I'm not very familiar with the library you're using but you might want to try manually setting the User-Agent header.

For example:

User-Agent: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko