webservice 接口通过 HTTP 获取数据

Posted 昊爷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webservice 接口通过 HTTP 获取数据相关的知识,希望对你有一定的参考价值。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Net;
 6 using System.Text;
 7 using System.IO;
 8 
 9 namespace testRsa
10 {
11 public class GetDataByHttp
12 {
13 
14 
15 public static string DoPost(string url, string data)
16 {
17 HttpWebRequest req = GetWebRequest(url, "POST");
18 byte[] postData = Encoding.UTF8.GetBytes(data);
19 Stream reqStream = req.GetRequestStream();
20 reqStream.Write(postData, 0, postData.Length);
21 reqStream.Close();
22 HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
23 Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
24 return GetResponseAsString(rsp, encoding);
25 }
26 
27 public static HttpWebRequest GetWebRequest(string url, string method)
28 {
29 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
30 req.ServicePoint.Expect100Continue = false;
31 req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
32 req.ContentType = "text/json";
33 req.Method = method;
34 req.KeepAlive = true;
35 req.UserAgent = "guanyisoft";
36 req.Timeout = 1000000;
37 req.Proxy = null;
38 return req;
39 }
40 
41 public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
42 {
43 StringBuilder result = new StringBuilder();
44 Stream stream = null;
45 StreamReader reader = null;
46 try
47 {
48 // 以字符流的方式读取HTTP响应
49 stream = rsp.GetResponseStream();
50 reader = new StreamReader(stream, encoding);
51 // 每次读取不大于256个字符,并写入字符串
52 char[] buffer = new char[256];
53 int readBytes = 0;
54 while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
55 {
56 result.Append(buffer, 0, readBytes);
57 }
58 }
59 finally
60 {
61 // 释放资源
62 if (reader != null) reader.Close();
63 if (stream != null) stream.Close();
64 if (rsp != null) rsp.Close();
65 }
66 
67 return result.ToString();
68 }
69 
70 
71 
72 }
73 }
74   
View Code

 

以上是关于webservice 接口通过 HTTP 获取数据的主要内容,如果未能解决你的问题,请参考以下文章

接口测试小白篇

springboot集成webservice接口

Spring AOP 自定义注解获取http接口及WebService接口入参和出参

webservice接口如何获取网站数据

WebService 天气预报webservice接口

如何基于这个请求http://www.webxml.com.cn/WebServices/WeatherWebService.asmx所提供的接口来获取东西?