在使用Unity的WWW来进行Post请求时候往往会失败。所以得找一个更加牛逼的方式。我们将用HttpWebRequest。
直接代码:
private string GetPost(Dictionary<string ,string> post) {
string str = "";
foreach (var item in post)
{
str += item.Key + "=" + item.Value+"&";
}
str = str.Remove(str.Length-1);
return str;
}
public void BuyTo()
{
Dictionary<string, string> post = new Dictionary<string, string>();
post.Add("name", "xxxx");
post.Add("appellation", "1");
post.Add("mobile", m_Phone);
post.Add("verificationCode", yanzhengma.text);
post.Add("province", "20");
post.Add("city", "219");
post.Add("orderInfo", "{\"39\":1,\"514\":1,\"519\":1,\"524\":1}");
post.Add("address", "");
post.Add("isDefault", "0");
post.Add("payMethod", "book");
post.Add("getCarAddress", "1");
post.Add("idCard", "xxxxxxxxxxxxxxxx");
string data = GetPost(post);
PostWebRequest (m_Url2 + "create",data);
}
private string PostWebRequest(string postUrl, string paramData)
{
print(postUrl+paramData);
byte[] bytes = Encoding.GetEncoding("gb2312").GetBytes(paramData);
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
webReq.ContentLength = bytes.Length;
using (Stream newStream = webReq.GetRequestStream())
{
newStream.Write(bytes, 0, bytes.Length);
}
using (WebResponse res = webReq.GetResponse())
{
Stream responseStream = res.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
string str = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
print(str);
return str;
}
}