我正在尝试将JSON数据(存在于文件中)传递给JSON POST方法。
但是收到HTTP 400错误(错误请求) - "远程服务器返回错误:(400)错误请求。"
请帮忙。
界面 - :
[OperationContract]
[WebInvoke(UriTemplate = "/JSON", Method = "POST")]
string CreatePersonFromJSONString(Person createPerson);
已实施的功能 - :
public string CreatePersonFromJSONString(Person createPerson)
{
createPerson.ID = (++personCount).ToString();
persons.Add(createPerson);
return new JavaScriptSerializer().Serialize(createPerson);
}
计划 - :
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.KeepAlive = false;
req.Method = Method.ToUpper();
if (("POST,PUT").Split(',').Contains(Method.ToUpper()))
{
Console.WriteLine("Enter JSON FilePath:");
string FilePath = Console.ReadLine();
content = (File.OpenText(@FilePath)).ReadToEnd();
req.ContentType = "application/json;";
//initiate the request
JavaScriptSerializer serializer = new JavaScriptSerializer();
var resToWrite = serializer.Deserialize<Person>(content);
StreamWriter PostData = new StreamWriter(req.GetRequestStream());
PostData.Write(resToWrite);
PostData.Flush();
PostData.Close();
}
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
输入文件内容 - :
{ "Age":"25",
"ID":"4",
"Name":"Ashish"
}
人员类 - :
[DataContract]
public class Person
{
[DataMember]
public string ID;
[DataMember]
public string Name;
[DataMember]
public string Age;
}
Uri - http://localhost:5171/RestService/JSON
方法 - POST
答案 0 :(得分:1)
[解决]
我不得不将数据写入更改为Request Stream。 无需反序列化JSON。
更改了程序部分 - :
public class TestThread {
public static void main(String[] args) {
Boolean bol = new Boolean(true);
(new Thread(new Odd(bol), "odd")).start();
(new Thread(new Even(bol), "even")).start();
}
}
public class Even implements Runnable {
private Boolean flag;
public Even(Boolean b) {
this.flag = b;
}
@Override
public void run() {
for (int i = 2; i < 20; i = i + 2) {
synchronized (flag) {
try {
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(1000);
flag.notify();
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Odd implements Runnable {
private Boolean flag;
public Odd(Boolean b) {
this.flag = b;
}
@Override
public void run() {
for (int i = 1; i < 20; i = i + 2) {
synchronized (flag) {
try {
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(1000);
flag.notify();
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
答案 1 :(得分:0)
对我来说,你的JSON无效。
在JSON中,属性名称必须是引号,所以:
{
"Age":"25",
"ID":"4",
"Name":"Ashish"
}