我是Windows Phone 7应用程序开发的新手。我试图使用POST方法在我的程序中调用一个URL,该方法需要一些参数。成功发布后,我应该以JSON格式获得响应。但我没有得到答复。我正在使用的代码是:
public void Submit()
{
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(someUrl, UriKind.Absolute));
myRequest.Method = "POST";
myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
public string url { get; set; }
private Dictionary<string, string> _parameters = new Dictionary<string, string>();
public Dictionary<string, string> parameters
{
get { return _parameters; }
set { _parameters = value; }
}
string boundary = "----------" + DateTime.Now.Ticks.ToString();
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
parameters.Add("userid", "0");
parameters.Add("locationid", "0");
writeMultipartObject(postStream, parameters);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
public void writeMultipartObject(Stream stream, object data)
{
StreamWriter writer = new StreamWriter(stream);
if (data != null)
{
foreach (var entry in data as Dictionary<string, string>)
{
WriteEntry(writer, entry.Key, entry.Value);
}
}
writer.Write("--");
writer.Write(boundary);
writer.WriteLine("--");
writer.Flush();
}
private void WriteEntry(StreamWriter writer, string key, object value)
{
if (value != null)
{
writer.Write("--");
writer.WriteLine(boundary);
if (value is byte[])
{
byte[] ba = value as byte[];
writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg");
writer.WriteLine(@"Content-Type: application/octet-stream");
//writer.WriteLine(@"Content-Type: image / jpeg");
writer.WriteLine(@"Content-Length: " + ba.Length);
writer.WriteLine();
writer.Flush();
Stream output = writer.BaseStream;
output.Write(ba, 0, ba.Length);
output.Flush();
writer.WriteLine();
}
else
{
writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""", key);
writer.WriteLine();
writer.WriteLine(value.ToString());
}
}
}
我找不到真正的问题。有人帮助我吗?
答案 0 :(得分:0)
也许不是一个“真正的”答案,但在处理帖子时我总是使用:http://postclient.codeplex.com/。这只是为了确保我没有用Request代码写任何错误。 试试吧。
答案 1 :(得分:0)
此示例来自http://northernlights.codeplex.com
/// <summary>
/// Send error report (exception) to HTTP endpoint.
/// </summary>
/// <param name="uri">The Endpoint to report to.</param>
/// <param name="exception">Exception to send.</param>
public void SendExceptionToHttpEndpoint(string uri, ExceptionContainer exception)
{
if (!this.AllowAnonymousHttpReporting)
{
return;
}
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(
r =>
{
try
{
HttpWebRequest request1 = (HttpWebRequest)r.AsyncState;
Stream postStream = request1.EndGetRequestStream(r);
string info = string.Format("{0}{1}{2}{1}AppVersion: {3}{1}", exception.Message, Environment.NewLine, exception.StackTrace, exception.AppVersion);
string postData = "&exception=" + HttpUtility.UrlEncode(info);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request1.BeginGetResponse(
s =>
{
try
{
HttpWebRequest request2 = (HttpWebRequest)s.AsyncState;
HttpWebResponse response = (HttpWebResponse)request2.EndGetResponse(s);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string response2 = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch
{
}
},
request1);
}
catch
{
}
},
webRequest);
}
catch
{
}
}
它会告诉您如何发布。
答案 2 :(得分:0)
WP7附带“Reactive Extensions”,它有助于一般的异步交互。此示例http://wp7guide.codeplex.com显示了如何将其用于HTTP帖子(以及其他内容)
警告:该示例适用于相当高级的应用程序,旨在显示许多其他内容,如单元测试,使用MVVM模式等。它可能比您需要的更复杂。
答案 3 :(得分:0)
我得到了解决方案:
{
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add(DataHolder.USER_ID, "0");
param.Add(DataHolder.DEFAULT_LOCATION_ID, "0");
PostClient proxy = new PostClient(param);
proxy.DownloadStringCompleted += new PostClient.DownloadStringCompletedHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(DataHolder.mainConfigFetchUrl, UriKind.Absolute));
}
void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
//Process the result...
string data = e.Result;
}
}
对于PostClient,我们需要一个可以从http://postclient.codeplex.com/
获取的WindowsPhonePostClient.dll