对HttpWebRequest进行了简单封装,支持get和post,支持超时,使用非常简单
使用时先创建一个 MyHttpRequest、MyHttp 对象
然后用MyHttp的PostAsync方法就能把请求发出去
例子
使用时先创建一个 MyHttpRequest、MyHttp 对象
然后用MyHttp的PostAsync方法就能把请求发出去
例子
using
YksHttp;
public
class
HttpCallBackEventArgs
{
public
int
ErrorCode = -1;
public
object
Result;
public
object
AttachData;
}
public
delegate
void
HttpCallBack(HttpCallBackEventArgs e);
private
void
HttpTestPost(Dispatcher disp, HttpCallBack callback)
{
MyHttpRequest request =
new
MyHttpRequest();
request.Method = Method.POST;
//get请求用Method.GET 同样用PostAsync函数
request.Accept =
"*/*"
;
request.UserAgent =
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"
;
request.ContentType =
"application/x-www-form-urlencoded"
;
request.AddHeader(
"Head1"
,
"JustForTest"
);
//添加自定义头
request.RequestBody =
"q=apple&t=dict&ut=default&ulang=ZH-CN&tlang=EN-US"
;
//发送二进制数据用request.RequestBytes
request.TimeOut = 10000;
//超时时间 10s
MyHttp http =
new
MyHttp();
http.PostAsync(request, (response) =>
{
HttpCallBackEventArgs e =
new
HttpCallBackEventArgs();
e.ErrorCode = (
int
)response.ResponseStatus;
if
(response.ResponseStatus == ResponseStatus.Completed)
{
Debug.WriteLine(response.ContentType);
foreach
(HttpHeader header
in
response.Headers)
{
Debug.WriteLine(
"{0}: {1}"
, header.Name, header.Value);
}
e.ErrorCode = (
int
)response.StatusCode;
if
(response.StatusCode == HttpStatusCode.OK)
{
e.Result = response.Content;
//response.Content是string类型,response.RawBytes是二进制数据
}
}
disp.BeginInvoke(callback, e);
});
}
private
void
HttpTestPostCallback(HttpCallBackEventArgs e)
{
_progressbar.Visibility = Visibility.Collapsed;
if
(e.ErrorCode == (
int
)HttpStatusCode.OK)
{
//请求返回
if
(e.Result
is
string
)
{
JObject o = JsonConvert.DeserializeObject(e.Result
as
string
)
as
JObject;
_txt.Text = o.ToString();
_txt.Visibility = Visibility.Visible;
_img.Visibility = Visibility.Collapsed;
}
}
else
{
MessageBox.Show(GetErrorDesc(e.ErrorCode),
""
, MessageBoxButton.OK);
}
}
private
void
OnClickButtonPost(
object
sender, RoutedEventArgs e)
{
_txt.Visibility = Visibility.Collapsed;
_img.Visibility = Visibility.Collapsed;
_progressbar.Visibility = Visibility.Visible;
HttpTestPost(Dispatcher, HttpTestPostCallback);
}
|
构造HttpHeader时,下列属性必须使用使用MyHttpRequest的属性设置,不能使用AddHeader方法
Accept 由 Accept 属性设置
Content-Type 由 ContentType 属性设置
User-Agent 由 UserAgent 属性设置
没找到在哪发布附件,代码例子只好放在我的网盘里了
http://dl.dbank.com/c0gm4bu4bg
https://skydrive.live.com/redir.aspx?cid=41d37a2871bb885e&resid=41D37A2871BB885E!114&parid=41D37A2871BB885E!109
附件中 httptest.rar是wp7 http代码例子, httpsimulator是pc上http模拟工具