dsdt66064367 2011-01-23 06:27
浏览 59
已采纳

使用Json.NET将Json String POST到远程PHP脚本

I am encountering an unusually strange behavior when POSTing a Json string to a PHP webserver. I use the JsonTextWriter object to create the Json string. I then send the Json string as a POST request. Please see comments. The HTML response in the code is returning the correct output, but when viewed in a browser, the web page displays either NULL or array(0) { }.

private void HttpPost(string uri, string parameters)
{
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded"; // <- Should this be "application/json" ?
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
try
{ // Send the Post Data 
    webRequest.ContentLength = bytes.Length;   
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);    

    Console.WriteLine(String.Format(@"{0}", byteString));     // <- This matches the Json object
}
catch (WebException ex)
{ //Handle Error }

try
{ // Get the response
    WebResponse webResponse = webRequest.GetResponse();
    if (webResponse == null) { return null; }
    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
    Console.WriteLine(sr.ReadToEnd().Trim());                // <- Server returns string response (full HTML page)
}
catch (WebException ex)
{ //Handle Error }
}  

Relevant PHP code on the server:

$json = json_encode($_POST);   # Not 'standard way'
var_dump(json_decode($json));

Any suggestions would be greatly appreciated.

Thanks

  • 写回答

1条回答 默认 最新

  • dtz63853 2011-01-23 06:50
    关注

    Try using "application/json" as the content type. Also, check the request logs or maybe do a port 80 trace if you can to view what's being sent to the server in the request body.

    You can also narrow the scope of the problem -- is it the C# code or the PHP code that's bad -- by writing a quick JQuery ajax function that sends some JSON to the PHP server. This isolation of the PHP code from the C# code will tell you if the PHP is at least working correctly. If it is, then the problem is in the C# code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题