Mthod: Post
Link: www.link.com
Headers:
1: appKey="ABC"
2: Content-Type="text/csv"
How to write the C# Script to send the data through post.?
Asked
Active
Viewed 1.9k times
1

EKNATH KULKARNI
- 394
- 1
- 5
- 13
-
I gone through link, I tried examples also. Their it is specified that the form.add method is used to upload the header but it wont work. And I need the post request by using UnityWebRequest. – EKNATH KULKARNI Aug 21 '18 at 05:46
2 Answers
3
public void Request()
{
try
{
string url = "www.link.com";
var request = UnityWebRequest.Post(url, "");
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Accept", "text/csv");
request.SetRequestHeader("appKey", "ABC");
StartCoroutine(onResponse(request));
}
catch (Exception e) { Debug.Log("ERROR : " + e.Message); }
}
private IEnumerator onResponse(UnityWebRequest req)
{
yield return req.SendWebRequest();
if (req.isError)
Debug.Log("Network error has occured: " + req.GetResponseHeader(""));
else
Debug.Log("Success "+req.downloadHandler.text );
byte[] results = req.downloadHandler.data;
Debug.Log("Second Success");
// Some code after success
}
This code is worked for me...

Oneiros
- 4,328
- 6
- 40
- 69

EKNATH KULKARNI
- 394
- 1
- 5
- 13
-
You can use promises with the UnityWebRequest to improve the quality of your code, check this OpenSource unity plugin => https://github.com/proyecto26/RestClient – jdnichollsc Aug 31 '18 at 01:55
2
You could do something like this :
void Start()
{
StartCoroutine(PostCrt());
}
IEnumerator PostCrt()
{
WWWForm form = new WWWForm();
form.AddField("appKey", "ABC");
form.AddField("Content-Type", "text/csv");
using (UnityWebRequest www = UnityWebRequest.Post("www.link.com", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Post Request Complete!");
}
}
}
Don't forget to call "using UnityEngine.Networking;" to be able to use UnityWebRequest.
Happy coding!

GhAyoub
- 525
- 4
- 11
-
I am getting error of cannot connect to destination host. The link is server api link. It works when I paste it on browser but hear it si giving me above error. – EKNATH KULKARNI Aug 20 '18 at 08:45
-
-
What this request exactly do? I think there is a problem of a missing Authorization header. – GhAyoub Aug 20 '18 at 08:58
-
I added the appKey,and content-type, accept headers . These headers are sufficient to get response. I tested it through postman. I am not getting what is missing. – EKNATH KULKARNI Aug 20 '18 at 09:01
-
Strange, I don't think that the problem is from the request but I do think that there is a problem with the url redirection. Sorry man I can't help you out. – GhAyoub Aug 20 '18 at 09:08
-
-
could you able to tell me how to read the response from above code – EKNATH KULKARNI Aug 20 '18 at 10:42
-