C#中的HttpWebRequest,HttpWebResponse

小编最近遇到了一个调用车辆违章的数据,也就是要调用其他相关机构Api接口,由于小编之前未接触过此类的编码,这个活可真是苦了小编,但小编想啊,如果可以把这个搞定,小编的技术就能再次进阶了,于是小编就开始疯狂的尝试,看了调用Api的接口也使用了,但是最后以屡屡失败告终,小编后来还联系了Api官网的技术服务人员,最后竟也没有搞定,于是乎看了一下师傅的逻辑,咦~~,你猜怎么着,灵感biu的一下就触不及防的出现在了我的脑海!…还是自己家的师傅靠谱啊,小编一定要记住恩师的好,不过也看到了自己的缺点呢,小编的C#根基也需要再努力巩固才行,啰嗦了一大堆,可都是心里话啊,来看代码吧!
这是官方C#调用接口的方法(属于我没有成功的那一块)

//using System.IO;
//using System.Text;
//using System.Net;
//using System.Net.Security;
//using System.Security.Cryptography.X509Certificates;

private const String host = "https://jisuqgclwz.market.alicloudapi.com";
private const String path = "/illegal/query";
private const String method = "GET";
private const String appcode = "你自己的AppCode";

static void Main(string[] args)
{
    String querys = "carorg=hangzhou&engineno=123456&frameno=229561&iscity=0&lsnum=AH5b57&lsprefix=%E6%B5%99&lstype=02&mobile=mobile";
    String bodys = "";
    String url = host + path;
    HttpWebRequest httpRequest = null;
    HttpWebResponse httpResponse = null;

    if (0 < querys.Length)
    {
        url = url + "?" + querys;
    }

    if (host.Contains("https://"))
    {
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
    }
    else
    {
        httpRequest = (HttpWebRequest)WebRequest.Create(url);
    }
    httpRequest.Method = method;
    httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
    if (0 < bodys.Length)
    {
        byte[] data = Encoding.UTF8.GetBytes(bodys);
        using (Stream stream = httpRequest.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
    }
    try
    {
        httpResponse = (HttpWebResponse)httpRequest.GetResponse();
    }
    catch (WebException ex)
    {
        httpResponse = (HttpWebResponse)ex.Response;
    }

    Console.WriteLine(httpResponse.StatusCode);
    Console.WriteLine(httpResponse.Method);
    Console.WriteLine(httpResponse.Headers);
    Stream st = httpResponse.GetResponseStream();
    StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
    Console.WriteLine(reader.ReadToEnd());
    Console.WriteLine("\n");

}

public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
    return true;
}

这便是小编的恩师和小编结合后的代码了

public void ProcessRequest(HttpContext context)
{
    string type = context.Request["type"].ToString();
    if (type.ToLower() == "querycarviolatedata")
    {
        string result = string.Empty;
        CarEntity carentity = new CarEntity();
        carentity.CurCity = context.Request["CurCity"].ToString();
        carentity.CarNum = context.Request["CarNum"].ToString();
        carentity.EngineNum = context.Request["EngineNum"].ToString();
        carentity.VINNum = context.Request["VINNum"].ToString();
        carentity.CarNum = context.Request["CarNum"].ToString();
        string appCode = "你自己的APPCODE";
        string aliyun = "https://jisuqgclwz.market.alicloudapi.com/illegal/query";
        String querys = "carorg" + carentity.CurCity + "=&engineno=" + carentity.EngineNum + "&frameno=" + carentity.VINNum + "&iscity=1&lsnum=" + carentity.CarNum.Substring(1, carentity.CarNum.Length - 1) + "&lsprefix=" + HttpUtility.UrlEncode(carentity.CarNum.Substring(0, 1)) + "&lstype=&mobile=";
        string url = aliyun + "?" + querys;
        HttpWebRequest httpRequest = null;
        HttpWebResponse httpResponse = null;

        if (aliyun.Contains("https://"))
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
        }
        else
        {
            httpRequest = (HttpWebRequest)WebRequest.Create(url);
        }

        httpRequest.Method = "GET";
        httpRequest.Headers.Add("Authorization", "APPCODE " + appCode);

        try
        {
            httpResponse = (HttpWebResponse)httpRequest.GetResponse();
        }
        catch (WebException ex)
        {
            WriteTextLog("车牌:" + carentity.CarNum + "查询违章有误:" + ex.Message, DateTime.Now);
            return;
        }
        using (Stream st = httpResponse.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8")))
            {
                result = reader.ReadToEnd();
            }
        }
        ArrayList rows = (ArrayList)JSON.Decode("[" + result + "]");
        Console.WriteLine(rows);
    }
}

private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
    return true;
}

小编这个代码并不完全,但是当小伙伴们将值传入方法中加入断点一直运行到result = reader.ReadToEnd();时,就可以看到接收过来的值了(最重要的),而后面的代码就需要根据需求来了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C#HttpWebRequest是一个用于发送HTTP请求的类。它可以用于向Web服务器发送GET、POST、PUT、DELETE等请求,并获取服务器响应。以下是HttpWebRequest的用法: 1. 创建HttpWebRequest对象 使用HttpWebRequest.Create方法创建HttpWebRequest对象,如下所示: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 其url是要请求的URL地址。 2. 设置请求方法 使用HttpWebRequest.Method属性设置请求方法,如下所示: request.Method = "GET"; 3. 设置请求头 使用HttpWebRequest.Headers属性设置请求头,如下所示: request.Headers.Add("User-Agent", "Mozilla/5.0"); 4. 设置请求参数 使用HttpWebRequest.GetRequestStream方法获取请求流,然后将请求参数写入请求流,如下所示: using (Stream stream = request.GetRequestStream()) { byte[] data = Encoding.UTF8.GetBytes("param1=value1&param2=value2"); stream.Write(data, 0, data.Length); } 5. 发送请求并获取响应 使用HttpWebRequest.GetResponse方法发送请求并获取响应,如下所示: using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); string result = reader.ReadToEnd(); } } 其result就是服务器响应的内容。 以上就是C#HttpWebRequest的用法。 ### 回答2: 我很抱歉,您没有提供问题或者主题,因此我无法提供相关的回答。请您给出更具体的问题或者主题,我会尽力为您提供满意的答案。感谢您的理解! ### 回答3: 抱歉,您没有提供问题或背景,无法提供回答。请提供问题或背景以获取更好的回答。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值