描述:近段时间写接口,还要调用别人的接口,写好写但是调用不知道啊!刚开始也知道怎么开始,感觉简单不就是调用吗?但是实施起来,汗...对我一个新手来说第一次接触,所以也是自学成才吧!下次登录的时候把源码带上....
//源码
string
jsonStr = Tools.Tool.getHttpRequestweb(
"你获得的接口地址"
);
string
sttNumber = Tools.Tool.GetTransData(jsonStr);
///
/// 解析JSON数据
///
///
///
public
static
string
GetTransData(
string
jsonText)
{
JavaScriptSerializer s =
new
JavaScriptSerializer();
Dictionary<
string
,
object
> JsonData = (Dictionary<
string
,
object
>)s.DeserializeObject(jsonText);
Dictionary<
string
,
object
> trades_sold_get_response = (Dictionary<
string
,
object
>)JsonData;
return
trades_sold_get_response[
"code"
].ToString();
}
if
(sttNumber ==
"1"
)
{
//我这儿1代表的是成功
}
public
static
string
getHttpRequestweb(
string
url)
{
string
result =
""
;
try
{ result = GrabHtml(url); }
catch
(Exception ex) {
return
ex.Message; }
return
result;
}
///
/// 网页抓取
///
///
///
public
static
string
GrabHtml(
string
urlName)
{
HttpWebResponse myHttpWebResponse;
string
webpathsource =
""
;
try
{
StringBuilder s =
new
StringBuilder(102400);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(urlName);
myHttpWebRequest.ContentType =
"application/x-www-form-urlencoded"
;
myHttpWebRequest.Accept =
"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*"
;
myHttpWebRequest.UserAgent =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"
;
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if
(myHttpWebResponse.StatusCode == HttpStatusCode.OK)
{
Stream rs = myHttpWebResponse.GetResponseStream();
MemoryStream stmMemory =
new
MemoryStream();
if
(myHttpWebResponse.ContentEncoding !=
null
&& myHttpWebResponse.ContentEncoding.Equals(
"gzip"
, StringComparison.InvariantCultureIgnoreCase))
{
GZipStream g =
new
GZipStream(rs, CompressionMode.Decompress);
byte
[] d =
new
byte
[20480];
int
l = g.Read(d, 0, 20480);
while
(l > 0)
{
s.Append(Encoding.Default.GetString(d, 0, l));
l = g.Read(d, 0, 20480);
}
webpathsource = s.ToString();
rs.Close();
}
else
{
StreamReader sr;
sr =
new
StreamReader(rs, System.Text.Encoding.UTF8);
webpathsource = sr.ReadToEnd();
rs.Close();
sr.Close();
}
return
webpathsource;
}
}
catch
(WebException ex)
{
myHttpWebResponse = (HttpWebResponse)ex.Response;
}
StreamReader srs =
new
StreamReader(myHttpWebResponse.GetResponseStream(), System.Text.Encoding.UTF8);
webpathsource = srs.ReadToEnd();
return
webpathsource;
}