问题描述
我移植自Android的应用程序到Windows Phone 8.1。我需要获取需要的OAuth认证的一些数据。我做了一些研究,我想我需要一个0条腿OAuth认证,因为我只有一个按键和放大器; ,秘密和URL来获取数据。
I'm porting an app from Android to Windows Phone 8.1. I need to fetch some data that needs an OAUTh authentication. I did some research and I think i need a 0-legged OAuth authentication, because i only have a key & secret and the url to get the data.
在Android项目的代码是这样的(JAVA):
In the Android project the code is like this (JAVA):
public JSONObject fetchData() {
try {
OAuthConsumer consumer = new DefaultOAuthConsumer(this.context.getString(R.string.consumer_key), this.context.getString(R.string.consumer_secret));
URL fullURL = new URL(url + "&start=" + start + "");
HttpURLConnection request = (HttpURLConnection) fullURL.openConnection();
consumer.sign(request);
request.setConnectTimeout(15000);
request.setRequestMethod("GET");
request.setRequestProperty("Accept", "application/json");
request.setRequestProperty("Accept-Encoding", "gzip");
request.connect();
switch (request.getResponseCode()) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return new JSONObject(sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
我的代码,我在的Windows phone 8.1的项目是(C#):
My code that i have in Windows phone 8.1 project is (C#):
public async Task<List<UiTEvent>> FetchEvents(ZoekResultatenExtras zre, double locationLatitude, double locationLongitude)
{
String completeURL;
List<UiTEvent> events = new List<UiTEvent>();
if (zre.CurrentLocation)
{
completeURL = SEARCH_EVENTS_URL + zre.SearchQuery + "&pt=" + locationLatitude + "," + locationLongitude + "";
}
else
{
completeURL = SEARCH_EVENTS_URL + zre.SearchQuery;
}
Debug.WriteLine(completeURL);
using (HttpClient client = new HttpClient())
{
OAuthBase oauth = new OAuthBase();
string normalizedUrl;
string normalizedqueryparameters;
var key = "MY_KEY";
var secret = "MY_SECRET";
var URL = new Uri("http://www.uitid.be/uitid/rest/searchv2/search?fq=type%3Aevent&fq=language%3Anl&group=event&rows=15&q=*%3A*&sfield=physical_gis&sort=geodist%28%29+asc&d=10&datetype=today&fq=-category_id%3A0.3.1.0.0&pt=51.0554827,3.7407583&start=0");
var oauth_nonce = oauth.GenerateNonce();
var oauth_timestamp = oauth.GenerateTimeStamp();
var oauth_signature_method = "HMAC-SHA1";
var oauth_signature = Uri.EscapeDataString(oauth.GenerateSignature(URL, key, secret, null, null, "GET", oauth_timestamp, oauth_nonce, out normalizedUrl, out normalizedqueryparameters));
String dfd = "OAuth oauth_consumer_key=\"" + key + "\", oauth_nonce=\"" + oauth_nonce + "\", oauth_signature=\"" + oauth_signature + "\", oauth_signature_method=\"" + oauth_signature_method + "\", oauth_timestamp=\"" + oauth_timestamp + "\", oauth_version=\"1.0\"";
client.DefaultRequestHeaders.Add("Authorization", dfd);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
using (HttpResponseMessage response = await (client.GetAsync(completeURL)))
{
if (response.IsSuccessStatusCode)
{
String content = await response.Content.ReadAsStringAsync();
}
}
}
return events;
}
我使用的
当我跑我的项目,我可以在查尔斯看到我总是收到响应代码401未授权
When I run my project I can see in Charles that I always receive the response code "401 Unauthorized"
什么我做错了。
我得到了OAuthBase。 CS库的工作!
我的代码是:
I got the OAuthBase.cs library working!My code is:
OAuthBase o = new OAuthBase();
var normalizedUrl = String.Empty;
var normalizedParameters = String.Empty;
var oauth_consumer_key = "MY KEY";
var oauth_consumer_secret = "MY SECRET";
var oauth_timestamp = o.GenerateTimeStamp();
var oauth_nonce = o.GenerateNonce();
var oauth_signature_method = "HMAC-SHA1";
var oauth_signature = o.GenerateSignature(new Uri(completeURL), oauth_consumer_key, oauth_consumer_secret, null, null, "GET", oauth_timestamp, oauth_nonce, out normalizedUrl, out normalizedParameters);
var oauth = "OAuth oauth_consumer_key=\"" + oauth_consumer_key + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_signature=\"" + Uri.EscapeDataString(oauth_signature) +"\",oauth_signature_method=\"" + oauth_signature_method + "\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_version=\"1.0\"";
var basestring = o.GenerateSignatureBase(new Uri(completeURL), oauth_consumer_key, null, null, "GET", oauth_timestamp, oauth_nonce, oauth_signature_method, out normalizedUrl, out normalizedParameters);
Debug.WriteLine(completeURL);
Debug.WriteLine(basestring);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", oauth);
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip");
using (HttpResponseMessage response = await (client.GetAsync(completeURL)))
{
if (response.IsSuccessStatusCode)
{
String content = await response.Content.ReadAsStringAsync();
Debug.WriteLine(content);
}
}
}
但我仍然有一个问题一些URL就是我想要获取数据。我发现这要归功于一个方便的网站:
But I still got a problem on some URL's where I want to fetch data. I found this thanks to a handy website:
- 的
- http://oauth.googlecode.com/svn../code/javascript/example/signature.html
我注意到,有时我即basestring解码是错误的,这就是为什么它给一个401未经授权错误。
I've noticed that sometimes my basestring decoding is wrong and that's why it give a 401 Unauthorized error.
好即basestring:
Good basestring:
GET&http%3A%2F%2Fwww.uitid.be%2Fuitid%2Frest%2Fsearchv2%2Fsearch&fq%3Dlanguage%253Anl%26fq%3Dtype%253Aevent%26group%3Devent%26oauth_consumer_key%3Def08c84b91c842bbf4f182d188dd4e57%26oauth_nonce%3DNjM1NDY3MTE0NzI3NTM3MDIw%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1411107473%26oauth_version%3D1.0%26q%3D%252A%253A%252A%26rows%3D15
我即basestring:
My basestring:
GET&http%3A%2F%2Fwww.uitid.be%2Fuitid%2Frest%2Fsearchv2%2Fsearch&fq%3Dlanguage%253Anl%26fq%3Dtype%253Aevent%26group%3Devent%26oauth_consumer_key%3Def08c84b91c842bbf4f182d188dd4e57%26oauth_nonce%3DNjM1NDY3MTE0NzI3NTM3MDIw%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1411107473%26oauth_version%3D1.0%26q%3D%2A%253A%2A%26rows%3D15
我在我的网址*字符不会得到像编码OAuth的希望吧。
I got * characters in my URL that doesn't got encoded like OAuth wants it.
有关我的解码我使用的方法:
For my decoding I use the method:
private static String BuildQueryString(List<StringKeyValue> parameters)
{
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
StringBuilder builder = new StringBuilder();
foreach (var pair in parameters.Where(p => !String.IsNullOrEmpty(p.Value)))
{
if (builder.Length > 0)
{
builder.Append("&");
}
builder.Append(Uri.EscapeDataString(pair.Key));
builder.Append("=");
builder.Append(Uri.EscapeDataString(pair.Value));
}
return builder.ToString();
}
我想我需要尽量使用RFC3986编码的..但我不知道如何实现它。
我发现这个相关的问题:
但Uri.HexEscape方法不会WP8.1工作
but the Uri.HexEscape method doesn't work in WP8.1
推荐答案
我发现我自己的问题的解决方案。
I found the solution for my own problem.
查找具有兼容的OAuth的库WP8.1:
首先u需要一个工作库,随着Windows Phone 8.1兼容。在我来说,我使用
First u need a working library that is compatible with Windows Phone 8.1. In my case I used the class OAuthBase.cs from https://code.google.com/p/oauth/issues/detail?id=223
编码您的网址和放大器;参数,所以它使用RFC3986(OAuth的利用了这)
我有很多与OAuth的问题(获取数据时401未经授权错误),因为我编码我的网址与方法 Uri.EscapeDataString()
但有问题保留字符,如*()! '[]
I had a lot of problems with OAuth (401 Unauthorized error when fetching data) because I encoded my URL with the method Uri.EscapeDataString()
but that had problem with reserved characters like * ( ) ! ' [ ] ,
所以,我搜索了一个解决方案,并发现这一点:的。 。唯一的问题是,Uri.HexEscape功能不会再在WP8.1所以我改变了方法的一些工作。
So I searched for a solution for that and found this: How to get Uri.EscapeDataString to comply with RFC 3986. The only problem was that the Uri.HexEscape function doesn't work anymore in WP8.1 so I changed the method a bit.
该方法可以在这里找到:
The method can be found here:
private static readonly string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ",", ")", "[","]" };
internal static string EscapeUriDataStringRfc3986(string value)
{
StringBuilder escaped = new StringBuilder(Uri.EscapeDataString(value));
for (int i = 0; i < UriRfc3986CharsToEscape.Length; i++)
{
switch (UriRfc3986CharsToEscape[i])
{
case "!":
escaped.Replace(UriRfc3986CharsToEscape[i], "%21");
break;
case "*":
escaped.Replace(UriRfc3986CharsToEscape[i], "%2A");
break;
case "'":
escaped.Replace(UriRfc3986CharsToEscape[i], "%27");
break;
case "(":
escaped.Replace(UriRfc3986CharsToEscape[i], "%28");
break;
case ",":
escaped.Replace(UriRfc3986CharsToEscape[i], "%2C");
break;
case ")":
escaped.Replace(UriRfc3986CharsToEscape[i], "%29");
break;
case "[":
escaped.Replace(UriRfc3986CharsToEscape[i], "%5B");
break;
case "]":
escaped.Replace(UriRfc3986CharsToEscape[i], "%5D");
break;
}
}
return escaped.ToString();
}
构建OAuth的头,并登录到HttpClient的
有关建设OAuth的头ü可以使用一些方法从OAuthBase.cs:
For building the OAuth header u can use some methods from OAuthBase.cs:
OAuthBase o = new OAuthBase();
var normalizedUrl = String.Empty;
var normalizedParameters = String.Empty;
var oauth_consumer_key = "MY KEY";
var oauth_consumer_secret = "MY SECRET";
var oauth_timestamp = o.GenerateTimeStamp();
var oauth_nonce = o.GenerateNonce();
var oauth_signature_method = "HMAC-SHA1";
var oauth_signature = o.GenerateSignature(new Uri(completeURL), oauth_consumer_key, oauth_consumer_secret, null, null, "GET", oauth_timestamp, oauth_nonce, out normalizedUrl, out normalizedParameters);
var oauth = "OAuth oauth_consumer_key=\"" + oauth_consumer_key + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_signature=\"" + Uri.EscapeDataString(oauth_signature) +"\",oauth_signature_method=\"" + oauth_signature_method + "\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_version=\"1.0\"";
建立OAuth的头字符串只需将它添加到HttpClient的后:
After building the OAuth header string you only need to add it to the HttpClient:
HttpClient client = new HttpClient()
client.DefaultRequestHeaders.Add("Authorization", oauth);
的完整代码:
String completeURL = EscapeUriDataStringRfc3986("http://www.myurl.be/*!(),");
OAuthBase o = new OAuthBase();
var normalizedUrl = String.Empty;
var normalizedParameters = String.Empty;
var oauth_consumer_key = "MY KEY";
var oauth_consumer_secret = "MY SECRET";
var oauth_timestamp = o.GenerateTimeStamp();
var oauth_nonce = o.GenerateNonce();
var oauth_signature_method = "HMAC-SHA1";
var oauth_signature = o.GenerateSignature(new Uri(completeURL), oauth_consumer_key, oauth_consumer_secret, null, null, "GET", oauth_timestamp, oauth_nonce, out normalizedUrl, out normalizedParameters);
var oauth = "OAuth oauth_consumer_key=\"" + oauth_consumer_key + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_signature=\"" + Uri.EscapeDataString(oauth_signature) +"\",oauth_signature_method=\"" + oauth_signature_method + "\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_version=\"1.0\"";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", oauth);
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip");
using (HttpResponseMessage response = await (client.GetAsync(completeURL)))
{
if (response.IsSuccessStatusCode)
{
String content = await response.Content.ReadAsStringAsync();
//DO SOMETHING WITH CONTENT
}
}
}
这篇关于如何做到0模式的OAuth中的Windows Phone 8.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!