using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
private String clientId = "3MVG959Nd8JMmavQaPxF2HrVGsn306RKnwTA7SSODtc5IUPODMMBgTAkn7zYz6iZT8WTdxfGdGOzDZxjAJO9c";
private String clientSecret = "6888796626501949852";
private String username = "mkintegrationapi@nbmedicalsystem.com.test";
private String password = "crm123456";
private String environment = "地址";
private String url = null;
private static String accessToken = null;
private static String instanceUrl = null;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
url = “地址”;
string postData = String.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}"
, clientId, clientSecret, username, password);
PostHttpUrl(url, postData);
}
public static string PostHttpUrl(string uri, string postData)
{
try
{
//string url = uri + "?" + postData;
byte[] data = Encoding.UTF8.GetBytes(postData);
//处理HttpWebRequest访问https有安全证书的问题( 请求被中止: 未能创建 SSL/TLS 安全通道。)
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); //发送地址
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";//提交方式
request.ContentLength = data.Length;
//request.
request.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//获取响应
Stream stream = response.GetResponseStream(); //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string result = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
JavaScriptSerializer Jss = new JavaScriptSerializer();
Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(result);
//通过键access_token获取值
accessToken = respDic["access_token"].ToString();
instanceUrl = respDic["instance_url"].ToString();
return ""; // 返回的数据
}
catch (Exception ex)
{
return "网络错误:" + ex.Message.ToString();
}
}
}
做的过程中遇到过400错误:造成原因是传参的时候大小写字母搞混,碰到过SSL安全认证,加上红色的代码解决!记录一下,省的忘记!