【发布时间】:2014-05-25 03:53:20
【问题描述】:
我有这段代码,我正在尝试连接到 windows8 应用程序的 php 基础 api 服务器。但是我没有得到任何结果,因为我知道如果我尝试调试它,则 url 是正确的并且变量已设置。 我是 windows8 应用程序和 c# 的新手,经过多次研究,这就是连接到 api 服务器的样子 请帮忙
private void Button_Click(object sender, RoutedEventArgs e)
{
var username="lucy";
var password="lucy";
var request = HttpWebRequest.Create("http://myURL/login.php?username="+username+"&password="+password) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/json";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Create the post data
string postData = JsonConvert.SerializeObject(postStream).ToString();
MessageDialog msgDialog1 = new MessageDialog(postData, "bayyanit");
msgDialog1.ShowAsync();
Debug.WriteLine(postData);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
// postStream.Close();
//Start the web request
try
{
request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request);
}
catch(Exception ex)
{
MessageDialog msgDialog = new MessageDialog(ex.ToString(), "bayyanit");
msgDialog.ShowAsync();
}
}
void GetResponceStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
MessageDialog msgDialog = new MessageDialog(result, "bayyanit");
msgDialog.ShowAsync();
}
}
【问题讨论】:
-
API 与语言无关。当您调用 API 时,您会以 json 或 xml 或任何其他格式读取响应,而不管使用什么语言对其进行编码。
-
@Guns 我是 windows8 应用程序的新手,正在查看我的代码,我期待来自服务器的 json 格式的响应。我错过了什么?
-
首先,您是否检查了您的 API 在指定格式下是否响应良好?
-
是的,我们检查过了,它正在响应。实际上它也适用于不同的移动平台(ios 和 android)@Guns
-
如果我是你,我会直接在浏览器中调试 api url,看看它是否返回了一些东西。因此,您可能应该直接在浏览器中调用 url myURL/login.php?username=username&password=password,或者使用带有 method=post 的表单制作一个 html 并在浏览器中运行它并检查它返回的内容。