application/json 这个 Content-Type 作为响应头大家肯定不陌生。实际上,现在越来越多的人把它作为请求头,用来告诉服务端(请求行、请求头、实体内容)中实体内容是序列化后的 JSON 字符串。
/// <summary> /// 向服务端请求服务 /// </summary> /// <param name="ServerPage">url字符串</param> /// <param name="json"></param> /// <returns></returns> public static string RegisterImageToServer(string ServerPage, string json) { //创建请求 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServerPage); request.Method = "POST"; request.Timeout = 2500; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; //告诉服务端(请求行、请求头、实体内容)实体内容的数据类型 //创建输入流 //string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters"); //paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(json); byte[] payload; //将Json字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(json); //设置请求的ContentLength request.ContentLength = payload.Length; //发送请求,获得请求流 Stream writer; try { writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象 } catch (Exception) { writer = null; Console.Write("连接服务器失败!"); return null; } //将请求参数写入流 writer.Write(payload, 0, payload.Length); writer.Close();//关闭请求流 //读取返回消息 string res = string.Empty; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); res = reader.ReadToEnd(); reader.Close(); } catch (Exception ex) { return null;//连接服务器失败 } return res; }