Http GetPost网络请求

Posted _小马哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Http GetPost网络请求相关的知识,希望对你有一定的参考价值。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ZhuoHuiSchoolRoom.ZhuoHuiClass
{
class HttpWebResponseUtility
{
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

/// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
}

/// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="str">json字符串</param>
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
/// <returns></returns>
public static HttpWebResponse CreatePostHttpResponse(string url, string str, Encoding requestEncoding)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
request = WebRequest.Create(url) as HttpWebRequest;

request.Method = "POST";
request.ContentType = "application/json";
request.UserAgent = DefaultUserAgent;


byte[] data = requestEncoding.GetBytes(str.ToString()); //将json转为二进制流
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

return request.GetResponse() as HttpWebResponse;
}

private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
}

 

 

/// <summary>
/// Get获取所有年级
/// </summary>
private void ClassSendGetHttp()
{
string tagUrl = "http://" + serviceIp + "/courseware/grade";
CookieCollection cookies = new CookieCollection();//如何从response.Headers["Set-Cookie"];中获取并设置CookieCollection的代码略
HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(tagUrl, null, null, null);

Stream stream = response.GetResponseStream(); //获取响应的字符串流
StreamReader sr = new StreamReader(stream); //创建一个stream读取流
string html = sr.ReadToEnd(); //从头读到尾,放到字符串html

JObject obj = Newtonsoft.Json.Linq.JObject.Parse(html);
string Status = obj["status"].ToString();
if (Status == "0")
{
JArray jar = JArray.Parse(obj["data"].ToString());
for (int i = 0; i < jar.Count; i++)
{
JToken js = JToken.Parse(jar[i].ToString());
classList.Add(js["gradeName"].ToString());
}
}
else
{
MessageBox.Show("年级获取失败");
}

}

 

/// <summary>
/// 发送POST请求到HTTP站点
/// </summary>
private void SendPostHttp()
{
string Url = "http://" + serviceIp + "/file/" + lblAddress.Text.ToString();
CoursewareClass courseClass = new CoursewareClass();
courseClass.coverPicture = "";
courseClass.gradeName = cmboxClass.Text.Trim().ToString();
courseClass.imageUrl = "";
courseClass.knowledges = btnKnow.Text.Trim().ToString();
courseClass.name = txtName.Text.Trim().ToString();
courseClass.pageNum = "";
courseClass.pptUrl = lblAddress.Text.Trim().ToString();
courseClass.subjectName = cmboxSubject.Text.Trim().ToString();
courseClass.uploadPersonNo = Global.getValues("TeacherNum");
string str = JsonConvert.SerializeObject(courseClass);
HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(Url, str, Encoding.UTF8);

Stream stream = response.GetResponseStream(); //获取响应的字符串流
StreamReader sr = new StreamReader(stream); //创建一个stream读取流
string html = sr.ReadToEnd(); //从头读到尾,放到字符串html
JObject obj = Newtonsoft.Json.Linq.JObject.Parse(html);
string Status = obj["status"].ToString();
if (Status == "0")
{
string ClassNum = obj["data"]["classNum"].ToString(); //获取classNum{"classNum":"10665"}
}

}

以上是关于Http GetPost网络请求的主要内容,如果未能解决你的问题,请参考以下文章

前端开发网络——Ajax(GETPOST)

网络请求之GETPOST请求

HttpUrlConnection发送GETPOST请求

Node.js 网络编程 (上)Web基础知识实现HTTP及GETPOST的创建

iOS开发 GETPOST请求方法:NSURLSession篇

计算机网络http协议