我正在尝试从WP7应用调用google URL shortner API,我首先尝试使用控制台应用:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"longUrl\":\"http://www.google.com/\"}";
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
Console.Read();
它工作正常,并且返回一切正常,但当我尝试在 Windows Phone应用上执行此操作时
private void button1_Click(object sender, RoutedEventArgs e)
{
testConnection();
}
private void testConnection()
{
if (!NetworkInterface.GetIsNetworkAvailable())
MessageBox.Show("There's no internet connection, please reconnect to the internet and try again");
else
{
var req = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
req.ContentType = "application/json";
req.Method = "POST";
req.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), req);
textBlock2.Text = "Done";
}
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data:
string postData = "http://www.google.com";
byte[] byteArray = Encoding.Unicode.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
textBlock1.Text= streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
}
}
代码总是转到try方法的catch并给出“not found”错误。
答案 0 :(得分:1)
SSL和不受信任的证书存在已知问题。当前的Windows Phone 7应用程序模型不支持使用SSL连接到需要ClientCertificates的网站(仅支持BasicAuthentication)。您可以在此处阅读相同的问题:http://forums.create.msdn.com/forums/p/65076/398730.aspx
答案 1 :(得分:0)
我有一个类似的问题(这是有道理的,因为我开始使用此代码作为我的示例...)当我更改以下代码时,它开始工作到我可以再次前进的地步。
......来自:
byte[] byteArray = Encoding.Unicode.GetBytes(postData);
...到(相当于):
byte[] byteArray = Encoding.UTF8.GetBytes(postData);