沒想到搞了半天,php那端一直接收不到json值
string json =
"{\"user\":\"test\"," +
"\"n\":\"2\"}";
var webAddr =
"http://";
var httpWebRequest =
(HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.Method =
"POST";
httpWebRequest.ContentType =
"application/json";
httpWebRequest.ContentLength =
json.Length;
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Close();
}
var httpResponse =
(HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new
StreamReader(httpResponse.GetResponseStream()))
{
var result =
streamReader.ReadToEnd();
//return result;
}
找了很久,原來是php那端看不懂,C#這邊傳過去的json格式
在php接收那端需加上
// Error handling is left as an exercise
$input = json_decode(file_get_contents('php://input'), true);
$input = json_decode(file_get_contents('php://input'), true);
這樣就行了,然後這是php端的改法
C#端也有另一種寫法
string postData = "user=" +
HttpUtility.UrlEncode("test") +
"&n=" +
HttpUtility.UrlEncode("2");
byte[] byteArray =
Encoding.ASCII.GetBytes(postData);
string postData = "json=" +
HttpUtility.UrlEncode(serializer.Serialize(p));
string postData = "json=" +
HttpUtility.UrlEncode(serializer.Serialize(p));
php端:
$json_array = json_decode($_POST['json']);
沒有留言:
張貼留言