[C#]定制化图像接口示例代码2
置顶
qqeip_joe 发布于2018-07-12 16:33 浏览:398 回复:4
0
收藏

private void button3_Click(object sender, EventArgs e)
{
//Post()

var image = File.ReadAllBytes("D:\\246.png");

// 如果有可选参数
String img64 = System.Convert.ToBase64String(image);

String param = "{\"top_num\":5,\"image\":\"" + img64 + "\"}";
String token = "24.14f1f66d780caf1c189a2a6048e4b733.2592000.1531641182.282335-11403414";


string Url = IRDATA_DETECT + "?access_token=" + token;

MessageBox.Show(Post(Url, param));

}

public string Post(string strURL, string jsonParas)
{
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
//request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "application/json";

//将Json字符串转化为字节
byte[] payload = System.Text.Encoding.UTF8.GetBytes(jsonParas);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流

Stream writer;
try
{
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
}
catch (Exception)
{
writer = null;
//Console.Write("连接服务器失败!");
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流

String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}

Stream s = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(s, encode);
strValue = readStream.ReadToEnd();

s.Close();
// Releases the resources of the Stream.
readStream.Close();

return strValue;//返回Json数据
}

收藏
点赞
0
个赞
共4条回复 最后由秀秀000521回复于2018-07-16 11:18
#5秀秀000521回复于2018-07-16

感谢提醒,已删除~

0
#4果断叫小黑回复于2018-07-14

楼上这个人一直在刷废话没人管管么?

0
#2goJhou回复于2018-07-14

很棒哦,你的代码将帮助到很多人!

0
TOP
切换版块