zzzj-ovo 2019-02-26 15:53 采纳率: 100%
浏览 1394
已采纳

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

使用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条回答

  • zzzj-ovo 2019-02-26 17:55
    关注

    协议原因,https应该改成http,不知道为什么python上面就可以通用,兜兜转转最后回到原点,python是真的坑。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?