我正在尝试让request_token在应用中使用twitter登录,但我总是得到401错误。我在dev.twitter中创建了我的应用程序,我有消费者密钥,密码和回调。
这是我的方法:
def readSomething(String url){
StringBuffer buffer = new StringBuffer();
try {
/**
* get the time - note: value below zero
* the millisecond value is used for oauth_nonce later on
*/
int millis = (int) System.currentTimeMillis() * -1;
int time = (int) millis / 1000;
/**
* Listing of all parameters necessary to retrieve a token
* (sorted lexicographically as demanded)
*/
def data = [
"oauth_nonce": String.valueOf(millis),
"oauth_signature":"",
"oauth_signature_method":"HMAC-SHA1",
"oauth_timestamp": String.valueOf(time),
"oauth_version":"1.0"
]
/**
* Generation of the signature base string
*/
String signature_base_string =
"POST&"+URLEncoder.encode(url, "UTF-8")+"&";
data.each{
// ignore the empty oauth_signature field
if(it.key != "oauth_signature") {
signature_base_string +=
URLEncoder.encode(it.key, "UTF-8") + "%3D" +
URLEncoder.encode(it.value, "UTF-8") + "%26";
}
}
// cut the last appended %26
signature_base_string = signature_base_string.substring(0,
signature_base_string.length()-3);
/**
* Sign the request
*/
def signingKey=URLEncoder.encode(CONSUMER_SECRET, "UTF-8")+"&"
Mac m = Mac.getInstance("HmacSHA1");
m.init(new SecretKeySpec(signingKey.getBytes(), "HmacSHA1"));
m.update(signature_base_string.getBytes());
byte[] res = m.doFinal();
String sig = String.valueOf(res.encodeBase64());
data["oauth_signature"] = sig;
/**
* Create the header for the request
*/
String header = "OAuth ";
data.each {
header += it.key+"=\""+it.value+"\", ";
}
// cut off last appended comma
header = header.substring(0, header.length()-2);
System.out.println("Signature Base String: "+signature_base_string);
System.out.println("Authorization Header: "+header);
System.out.println("Signature: "+sig);
String charset = "UTF-8";
URLConnection connection = new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
connection.setRequestProperty("Authorization", header);
OutputStream output = connection.getOutputStream();
output.write(header.getBytes(charset));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
println"reader "+reader
String read;
while((read = reader.readLine()) != null) {
buffer.append(read);
}
}
catch(Exception e) {
e.printStackTrace();
}
println"buffer "+buffer
println"buffer "+buffer.getClass()
println"buffer "+buffer.toString()
return buffer.toString()
}
它有什么问题吗?
我相信我没有正确签名而且oauth_signature是错误的。有没有办法检查这个签名是否正常?
我尝试这样做(http://stackoverflow.com/questions/2964392/implement-oauth-in-java)但仍然无法正常工作,其他任何想法可能会发生什么?
提前致谢