Question by
PiroKun · Oct 12, 2017 at 08:22 PM ·
jsonwebservice
Problem with unitywebservice and json. Status Code: 400
Hi! I´m using http://jsonplaceholder.typicode.com for get running an example code using json and unitywebservice, but i get Status Code:400. Where is the problem? The code looks very straightforward. Thanks!
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class ConnectTest : MonoBehaviour {
void Start () {
string url = "http://jsonplaceholder.typicode.com/posts";
string jData = "{title:'foo',body:'bar',userId:1}";
StartCoroutine(Post(url, jData));
}
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
Debug.Log("Status Code: " + request.responseCode);
}
}
Comment
Answer by timkulp · Oct 13, 2017 at 03:27 AM
Hi PiroKun,
Have you checked what the HTTP message is coming form Unity via Fiddler or a similar tool? I have found that sometimes there are some unexpected formats, characters, encodings that come with the UnityWebRequest object. For an API that I was working with I kept getting 400 errors due to an encoding that was being applied that I didn't see until Fiddler caught it.
Hope that helps. Tim