c# 发送http请求

public string HttpPost(string postDataStr)
{
try
{
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(APIStr);//这是服务器IP
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
//request.CookieContainer = cookie;

//设定编码
Encoding encoding = Encoding.UTF8;
//先将对像序例化成JSON字串,然后再用流写入byte[]
//byte[] userByteData = encoding.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(obj));
byte[] userByteData = encoding.GetBytes(postDataStr);
Stream stream = request.GetRequestStream();
stream.Write(userByteData, 0, userByteData.Length);
stream.Close();

//Stream myRequestStream = request.GetRequestStream();
//StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
//myStreamWriter.Write(postDataStr);
//myStreamWriter.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// response.Cookies = cookie.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
catch(Exception ex)
{
throw;
}
}

这是拼接Post请求参数
public string getPostStr(string op, string ac, string json)
{
//var jObject = JObject.Parse(json);
string jsonStr = "op=" + op + "&action=" + ac + "&Login_type=chain&data=" + json+"&";
return jsonStr;
}

JSONHelper jsonHelper = new JSONHelper();

string postStr = "";//post 参数
string jsonStr = jsonHelper.getPostStr("", "", postStr);
string retureJson= jsonHelper.HttpPost(jsonStr);
var jObject = JObject.Parse(retureJson);

 

有看不懂可以直接联系我!

posted on 2015-02-06 18:30  zrSoldier  阅读(253)  评论(0编辑  收藏  举报