在调用一个客户写的接口的时候,需要是get请求,并且参数是个json类型的数据,通过postman测试,没问题,可以获取到值,但是通过代码却一直都不行,就是报错说,不支持的谓词等。
后来在朋友的帮助下,找到了一个网址,最后试了居然可以了。参考网址是:https://blog.csdn.net/actionteam/article/details/119341811
通过测试,发现跟我的区别就是我少了一段代码,加上后,我之前的代码居然也可以了。
完整代码如下,其中红色字体为起作用的代码
/// <summary> /// 发送get请求 参数拼接在url后面 /// </summary> /// <param name="url">请求接口地址</param> /// <returns></returns> public static string HttpGet(string url, string param = "", int timeOut = 60000) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Proxy = null; request.KeepAlive = false; request.Method = "GET"; request.ContentType = "application/json; charset=UTF-8"; request.AutomaticDecompression = DecompressionMethods.GZip; if (!string.IsNullOrEmpty(param)) { byte[] data = Encoding.UTF8.GetBytes(param); request.ContentLength = data.Length; var type = request.GetType(); var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request); var methodType = currentMethod.GetType(); methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false); using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); if (response != null) { response.Close(); } if (request != null) { request.Abort(); } return retString; } catch (Exception ex) { Log4NetHelper.GetLogger().Error(ex); Log4NetHelper.GetLogger().Error(url + ":" + param); return "-1"; } }