using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using System.Threading;
public class ResultModel
{
public string errcode { get; set; }
public string errmsg { get; set; }
public string hashkey { get; set; }
}
private const String host = "http://apis.5118.com";
private const String path = "/naotu/related";
private const String method = "POST";
private const String apikey = "你要调用的接口apikey";
private void Form1_Load(object sender, EventArgs e)
{
String querys = "";
String bodys = "keyword=keyword";
String url = host + path;
string str = SendPost(querys, bodys, url);
Console.WriteLine(str);
Console.WriteLine("\n");
ResultModel model = JsonConvert.DeserializeObject<ResultModel>(str);
while (true)
{
if (!string.IsNullOrEmpty(model.hashkey))
{
bodys = "hashkey=hashkey";
string jsonStr = SendPost(querys, bodys, url);
Console.WriteLine(jsonStr);
break;
}
else
{
Thread.Sleep(60000);
str = SendPost(querys, bodys, url);
model = JsonConvert.DeserializeObject<ResultModel>(str);
}
}
}
private static string SendPost(string querys, string bodys, string url)
{
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", apikey);
//根据API的要求,定义相对应的Content-Type
httpRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
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"));
return reader.ReadToEnd();
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}