我对这个问题非常厌倦
我尝试通过客户端ID和客户端密码值和范围值(如
)首先登录Google联系人scope=https://www.google.com/m8/feeds/&response_type=code
并设置重定向URI。
在服务器端我管理了像
这样的标题response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
response.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Max-Age", "1728000");
和JQuery函数在
之下function ok(){
$.ajax({
type : 'post',
dataType: "json",
contentType:"application/x-www-form-urlencoded; charset=utf-8",
crossDomain:true,
cache : true,
data :
{
code : '<%=auth_code%>',client_id: '<%=client_id%>',
client_secret : '<%=client_secret%>',redirect_uri: '<%=redirect_uri%>',
max_results : <%=max_results%>,grant_type:'authorization_code'
},
url : 'https://accounts.google.com/o/oauth2/token',
success : function(data){
//alert("success "+data['access_token']);
var accesstoken = data['access_token'];
//alert(accesstoken);
var url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results=<%=max_results%>&oauth_token='+accesstoken;
//alert(url);
$.ajax({
url : url,
dataType: "xml",
type: "GET",
success : function(data){
alert("success "+data);
$(data).find("entry").each(function(){
for(var i=0 ;i<$(this)[0].children.length;i++){
if($(this)[0].children[i].nodeName == "gd:email")
console.log($(this)[0].children[i].attributes[1].textContent);
}
});
},
error: function(jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
},
error: function(jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
}
答案 0 :(得分:0)
以下是客户端多次请求的问题。
上面的代码使用JQuery在ajax中执行多个请求。
相比之下,我在服务器端(Servlet)点击了URL。
现在代码像
$.ajax({
type : 'post',
dataType: "json",
contentType:"application/x-www-form-urlencoded; charset=utf-8",
crossDomain:true,
cache : true,
data :
{
code : '<%=auth_code%>'
},
url : '<%=request.getContextPath()%>/GetAccessTokenServlet',
success : function(data){
alert(data);
},
error: function(jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
和servlet“GetAccessTokenServlet”类似
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("code");
String grant_type = "authorization_code";
String charset = "UTF-8";
String accessparameters = String.format("client_id=%s&client_secret=%s&redirect_uri=%s&max_results=%s&code=%s&grant_type=%s",
URLEncoder.encode(client_id, charset),URLEncoder.encode(client_secret, charset),URLEncoder.encode(redirect_uri, charset),
URLEncoder.encode(max_results, charset),URLEncoder.encode(code, charset),URLEncoder.encode(grant_type, charset));
String resultStr = "";
try{
URL accesstoken_url = new URL("https://accounts.google.com/o/oauth2/token");
HttpURLConnection accesstokenConnection = (HttpURLConnection) accesstoken_url.openConnection();
// treeConnection.setRequestMethod("GET");
accesstokenConnection.setDoOutput(true);
accesstokenConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
accesstokenConnection.setRequestProperty("Accept-Charset", charset);
try {
accesstokenConnection.getOutputStream().write(accessparameters.getBytes(charset));
}
finally {
accesstokenConnection.getOutputStream().close();
}
BufferedReader accesstokenReader = new BufferedReader(new InputStreamReader(accesstokenConnection.getInputStream()));
String line;
while((line = accesstokenReader.readLine()) != null){
resultStr+=line;
}
System.out.println(resultStr);
JSONObject jsonObject = new JSONObject(resultStr);
String oauth_token = String.valueOf(jsonObject.get("access_token"));
URL contactURL = new URL("https://www.google.com/m8/feeds/contacts/default/full?oauth_token="+oauth_token);
HttpURLConnection contactConnection = (HttpURLConnection) contactURL.openConnection();
contactConnection.setRequestMethod("GET");
contactConnection.setDoOutput(true);
contactConnection.setRequestProperty("Content-Type", "text/xml");
contactConnection.setRequestProperty("Pragma", "no-cache");
contactConnection.setRequestProperty("Cache-Control", "no-cache");
contactConnection.setRequestProperty("Connection", "keep-alive");
contactConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
System.out.println("length: "+contactConnection.getContentLength());
System.out.println("type: "+contactConnection.getContentType());
BufferedReader contactReader = new BufferedReader(new InputStreamReader(contactConnection.getInputStream()));
String contactLine;
String contactStr = "";
while ((contactLine = contactReader.readLine()) != null) {
contactStr += contactLine;
//System.out.println("contactLine: "+contactLine);
if(contactLine.contains("gd:email")){
String[] gdEmail = contactLine.split(" ");
for(int i=0;i<gdEmail.length;i++){
if(gdEmail[i].startsWith("address")){
System.out.println(gdEmail[i].substring(gdEmail[i].indexOf("=")+1));
}
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
response.getWriter().write(resultStr.toString());
}
此代码返回朋友的电子邮件地址。
答案 1 :(得分:0)
<?php
$url ="https://accounts.google.com/oenter code here/oauth2/token";
$fields = array(
"client_id"=>"XXXXXXXXXX-j4r6g3XXXXXXXXXXXXXlg6f9lmn.apps.googleusercontent.com", //static data
"client_secret"=>"FYefMXXXXXXXXXXXXXXzI4P", //static data
"refresh_token"=>"1/haH1XXXXXXXXXXXXXXXXXXjQn9zY2_1xLg", //static data
"grant_type"=>"refresh_token" //static data
);
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST,count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$lResponse_json = curl_exec($ch);
//close connection
curl_close($ch);
$responseObj = json_decode($lResponse_json,true);
&GT;
//创建刷新令牌请关注https://developers.google.com/android-publisher/authorization 一旦创建刷新令牌使用上面的代码来获取访问令牌一次又一次地使用API // javascript不支持跨域原始策略,因此您必须使用curl来克服此问题