UnityWebRequest, C# request.accept equivalent?
Hello, I have tried searching for this question but I either cannot word it properly, or I just don't understand it enough to know what to look for.
I am trying to send a UnityWebRequest, but I need to specify the data type to accept from the API. In standard C# it would look like this:
public class MainClass {
public static void Main (string[] args) {
var request = (HttpWebRequest)WebRequest.Create("https://www.website.com/apistuff");
request.Method = "GET";
request.Headers["Authorization"] = "Bearer <TOKEN>";
request.Accept = "application/json";
var response = (HttpWebResponse)request.GetResponse();
Console.WriteLine (response.StatusCode);
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine (responseString);
}
}
So far, I think I know how to assign the Header properly using the UnityWebRequest.SetHeader(name,value) method. What I'm missing is the Unity equivalent to the standard C# request.Accept to make sure that I get the correct data type. Basically, what I have in the code for Unity is this:
IEnumerator GetData()
{
Button1.text = "Loading...";
string uri = "https://website.com/api";
using (UnityWebRequest request = UnityWebRequest.Get(uri))
{
request.SetRequestHeader("Authorization", "Bearer " + APIKey);
yield return request.SendWebRequest();
if ((request.isNetworkError) || (request.isHttpError))
{
Button.text = "Error!";
Debug.Log("Request Error:" + request.error);
}
else
{
if (request.isDone)
{
var quote = JsonConvert.DeserializeObject<Response>(request.downloadHandler.text); //This fits the Json data to a preset model
if (request.downloadHandler.text != null && request.downloadHandler.text != "")
{
Response = request.downloadHandler.text;
}
}
}
}
}
Any help at all would be wonderfully accepted, thank you for your time.
Answer by Dahaka666 · Jan 19 at 09:18 PM
I figured it out, the request.accept is another form of a header, and can be assigned in the following way:
IEnumerator GetData()
{
Button1.text = "Loading...";
string uri = "https://website.com/api";
using (UnityWebRequest request = UnityWebRequest.Get(uri))
{
request.SetRequestHeader("Authorization", "Bearer " + APIKey);
request.SetRequestHeader("Accept", "application/json");
yield return request.SendWebRequest();
if ((request.isNetworkError) || (request.isHttpError))
{
Button1.text = "Error!";
Debug.Log("Request Error:" + request.error);
}
}
}