FoxOnTheRoof
FoxOnTheRoof
2019-02-26 15:53

由于异常的数据包格式,握手失败

5
  • c#
  • python
  • microsoft
  • visual studio

使用HttpWebRequest 类Post数据,报错 基础连接已经关闭: 接收时发生错误:由于异常的数据包格式,握手失败。
pathon脚本测试url能获取数据,但是改成C#就不行了!
C#代码:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072| SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, error) =>
{
return true;
};
ServicePointManager.CheckCertificateRevocationList = false;
strUserName = "admin";
strPassWord = "admin";
string getJson = string.Empty;

        string url = "https://10.0.18.41:8081/oauth/token";  //request url
        string postdata = "grant_type=password&username=" + strUserName + "&password=" + strPassWord;  //body         
        getJson = PostUrl(url, postdata);

static string PostUrl(string strUrl, string strPostData)
{
Console.WriteLine(strPostData);
string strReturnValue = string.Empty;
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(strUrl);
try
{
httpReq.Method = "POST";
httpReq.Timeout = 100000;//设置请求超时时间,单位为毫秒
httpReq.KeepAlive = false;
httpReq.ProtocolVersion = HttpVersion.Version10;
httpReq.Accept = "application/json";
httpReq.ContentType = "application/x-www-form-urlencoded";
//httpReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
if (strUserName != string.Empty || strPassWord != string.Empty)
{
string usernamePassword = "test:test";
httpReq.Credentials = CredentialCache.DefaultCredentials;
httpReq.Headers.Add("Cache-Control", "no-cache");
httpReq.Headers.Add("X-Requested-With", "XMLHttpRequest");

httpReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(usernamePassword)));
}
Console.WriteLine(httpReq.Headers);
byte[] bytePostData = Encoding.UTF8.GetBytes(strPostData);
httpReq.ContentLength = bytePostData.Length;

            using (Stream reqStream = httpReq.GetRequestStream())
            {
                reqStream.Write(bytePostData, 0, bytePostData.Length);
                reqStream.Close();
            }
            HttpWebResponse httpResponse = (HttpWebResponse)httpReq.GetResponse();
            Stream stream = httpResponse.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                strReturnValue = reader.ReadToEnd();
                reader.Close();
            }
            if (httpResponse != null)
            {
                httpResponse.Close();
            }
            if (httpReq != null)
            {
                httpReq.Abort();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return strReturnValue;
    }

Python代码:
import http.client, urllib.parse, json
import base64

api_host1='10.0.18.41:8081'

bearer = base64.b64encode(bytes('test:test','utf-8'))
#获取用户token
def getAccessToken(username, password):
params = 'grant_type=password&username=' + username + '&password=' + password
print(params)
headers = {"Cache-Control": "no-cache", "X-Requested-With":"XMLHttpRequest" }
headers["Content-Type"] = 'application/x-www-form-urlencoded'
headers["Authorization"] = 'Basic ' + bearer.decode('utf-8')
print(headers)
url = "https://10.0.18.41:8081/oauth/token"
conn = http.client.HTTPConnection(api_host1)
print(url)
conn.request("POST", url, params, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read().decode('utf-8')
print(data)
r = json.loads(data)
token = r['access_token']
conn.close()
return token
print(getAccessToken('admin','admin'))

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答