403 Forbidden Unity3D C#

2019-07-17 09:14发布

问题:

I've been trying to get the information from this link: HIDDEN

Here is my current code

public static string newsLink = "HIDDEN";
public static readonly List<string> newsList = new List<string>();

void Start () {
    DontDestroyOnLoad (gameObject);
    StartCoroutine (GetNews ());
}

IEnumerator GetNews(){
    WWW w = new WWW (newsLink);
    yield return w;
    if (w.error != null) {
        print (w.error);
    } else {
        List<string>temp = w.text.Split (']').ToList ();
        foreach(string a in temp)
        {
            newsList.Add (a);
        }
        w.Dispose ();
    }
  }
}

in the debugger I get the error message of 403 Forbidden

回答1:

The url you are making request to requires that you provide the User-Agent to identify who you are. You may need other headers to get the appropriate response but the User-Agent header is required to remove that 403 error thrown by the server.

Create the User-Agent (pretend to be Chrome)

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> ht = new Dictionary<string, string>();
ht["User-Agent"] = userAgent;

Then create the WWW request with the header

WWW w = new WWW(newsLink, null, ht);
yield return w;

Note that you may end up receiving your Html and Javascript code instead of the message you get when you visit the link from a web browser. That's because your client(Unity) does not support Javascript and cannot execute your Javascript code.You have to re-write the server code with php. Finally, use json instead of ] or | to seperate your messages.



标签: c# unity3d web