如何发布JSON到服务器?
以下是我正在使用的代码:
// create a request HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; // turn our request string into a byte stream byte[] postBytes = Encoding.UTF8.GetBytes(json); // this is important - make sure you specify type this way request.ContentType = "application/json; charset=UTF-8"; request.Accept = "application/json"; request.ContentLength = postBytes.Length; request.CookieContainer = Cookies; request.UserAgent = currentUserAgent; Stream requestStream = request.GetRequestStream(); // now send it requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); // grab te response and print it out to the console along with the status code HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string result; using (StreamReader rdr = new StreamReader(response.GetResponseStream())) { result = rdr.ReadToEnd(); } return result;
当我运行这个,我总是得到500内部服务器错误。
我究竟做错了什么?
我做这件事的方式是:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"user\":\"test\"," + "\"password\":\"bla\"}"; streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
我写了一个库以更简单的方式执行这个任务,它在这里: https : //github.com/ademargomes/JsonRequest
希望能帮助到你。
通过利用JavaScriptSerializer
的Serialize
方法来提供对象的隐式转换为JSON,可以改进Ademar的解决scheme。
此外,可以利用using
语句的默认function来省略明确调用Flush
和Close
。
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = new JavaScriptSerializer().Serialize(new { user = "Foo", password = "Baz" }); streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
除了肖恩的post之外,没有必要嵌套使用陈述。 通过using
StreamWriter,它将在块的末尾被刷新并closures,因此不需要显式调用Flush()
和Close()
方法:
var request = (HttpWebRequest)WebRequest.Create("http://url"); request.ContentType = "application/json"; request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { string json = new JavaScriptSerializer().Serialize(new { user = "Foo", password = "Baz" }); streamWriter.Write(json); } var response = (HttpWebResponse)request.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
照顾你正在使用的内容types:
application/json
来源:
RFC4627
其他职位
如果你需要调用asynchronous然后使用
var request = HttpWebRequest.Create("http://www.maplegraphservices.com/tokkri/webservices/updateProfile.php?oldEmailID=" + App.currentUser.email) as HttpWebRequest; request.Method = "POST"; request.ContentType = "text/json"; request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request); private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; // End the stream request operation Stream postStream = request.EndGetRequestStream(asynchronousResult); // Create the post data string postData = JsonConvert.SerializeObject(edit).ToString(); byte[] byteArray = Encoding.UTF8.GetBytes(postData); postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); //Start the web request request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request); } void GetResponceStreamCallback(IAsyncResult callbackResult) { HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult); using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream())) { string result = httpWebStreamReader.ReadToEnd(); stat.Text = result; } }
这个选项没有提到:
using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:9000/"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var foo = new User { user = "Foo", password = "Baz" } await client.PostAsJsonAsync("users/add", foo); }
我最近想出了一个简单的方法来发布JSON,从我的应用程序模型转换额外的步骤。 请注意,您必须为您的控制器创build模型[JsonObject]以获取值并进行转换。
请求:
var model = new MyModel(); using (var client = new HttpClient()) { var uri = new Uri("XXXXXXXXX"); var json = new JavaScriptSerializer().Serialize(model); var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); var response = await Client.PutAsync(uri,stringContent).Result; ... ... }
模型:
[JsonObject] [Serializable] public class MyModel { public Decimal Value { get; set; } public string Project { get; set; } public string FilePath { get; set; } public string FileName { get; set; } }
服务器端:
[HttpPut] public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model) { ... ... }
一些不同的和干净的方式来实现这一点是通过使用HttpClient像这样:
public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject) { using (var client = new HttpClient()) { HttpResponseMessage response = new HttpResponseMessage(); try { response = await client.PostAsJsonAsync(url, resultObject); } catch (Exception ex) { throw ex } return response; } }
var data = Encoding.ASCII.GetBytes(json);
byte[] postBytes = Encoding.UTF8.GetBytes(json);
使用ASCII而不是UFT8