web 服务
Posted ym296900664
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了web 服务相关的知识,希望对你有一定的参考价值。
#region HttpRequestGetpublic string HttpRequestGet(string url)
return HttpRequestGet(url, WebRequestMethods.Http.Get, "");
public string HttpRequestPost(string url, string data)
return HttpRequestGet(url, WebRequestMethods.Http.Post, data);
private string HttpRequestGet(string url, string method, string data)
var request = WebRequest.Create(url);
request.Method = method;
if (method == WebRequestMethods.Http.Post)
byte[] buffer = Encoding.Default.GetBytes(data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
var streamRequest = request.GetRequestStream();
streamRequest.Write(buffer, 0, buffer.Length);
streamRequest.Close();
var response = request.GetResponse();
var streamResponse = response.GetResponseStream();
if (streamResponse == null) return "";
var reader = new StreamReader(streamResponse, Encoding.Default);
var result = reader.ReadToEnd();
streamResponse.Close();
reader.Close();
return result;
#endregion
public string WebClientGet(string url)
var client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
var stream = client.OpenRead(url);
if (stream == null) return "";
var reader = new StreamReader(stream, Encoding.Default);
var result = reader.ReadToEnd();
stream.Close();
reader.Close();
return result;
or
public static string DoGet(string url)
try
string serviceAddress = url;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceAddress);
request.ContentType = "application/json";request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
string result = dataStream.ReadToEnd();
return result;
catch
MessageBox.Show("远程服务无法连接,请查看是否连接网络!", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return null;
以上是关于web 服务的主要内容,如果未能解决你的问题,请参考以下文章