Logging Http request and response body - grails

I am trying to figure out how to log every request and its associated response that comes into my application. Currently I have created a Grails interceptor that captures the request and response. The issue that I keep running into is if I log the request body before it reaches the controller then the resource is consumed by my logger and request body is null. So I tried logging the request body after it's been processed by the controller. The problem with that is then the input stream is closed and I can no longer access it.
this is my interceptor:
import grails.plugin.springsecurity.SpringSecurityService
import javax.servlet.ServletRequest
class HttpLoggingInterceptor {
SpringSecurityService springSecurityService
HttpLoggingService httpLoggingService
HttpLoggingInterceptor() {
match(controller: "*")
}
boolean before() {
httpLoggingService.logRequest(request, response, springSecurityService.principal)
true
}
}
This is the httpLoggingService:
import grails.transaction.Transactional
import org.apache.commons.io.IOUtils
import org.springframework.security.core.userdetails.User
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletRequestWrapper
import javax.servlet.http.HttpServletResponse
import java.nio.charset.StandardCharsets
#Transactional
class HttpLoggingService {
static final String CR = "\r\n"
def logRequest(HttpServletRequestWrapper request, HttpServletResponse response, User user) {
log.debug("REQUEST:${CR}" +
"Request URL: ${request?.method} ${request?.requestURL}${CR}" +
"Request QueryString: ${request?.queryString}${CR}" +
"Request Body : ${getRequestBody(request)}" +
"Request Client IP: ${request?.remoteAddr}${CR}" +
"Request User: ${getUserInfo(user)}${CR}" +
"Request Headers: ${getRequestHeaders(request)}${CR}" +
"Request Query String Parameters: ${getRequestParameters(request)}${CR}" +
"Response Status: ${response?.status}${CR}" +
"Respones Body: ${getResponseBody(response)}" +
"Response Properties: ${response?.properties}${CR}" +
"Response Headers: ${getResponseHeaders(response)}${CR}" +
CR
)
}
private String getUserInfo(User user) {
String userInfo = null
if (user instanceof CipUserDetails) {
userInfo = "${user?.username} [${user?.fullName}] - ${user?.authorities[0]?.role}"
}
userInfo
}
private String getRequestBody(HttpServletRequestWrapper request) {
String requestBody = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8)
requestBody
}
private String getRequestParameters(HttpServletRequest request) {
Map parameterMap = request?.parameterMap
String parameterString = ""
for (String name : request?.parameterNames) {
parameterString += "${CR} ${name}=${parameterMap?.get(name)}"
}
parameterString
}
private String getRequestHeaders(HttpServletRequest request) {
String parameterString = ""
for (String name : request.headerNames) {
parameterString += "${CR} ${name}=${request?.getHeader(name)}"
}
parameterString
}
private String getResponseHeaders(HttpServletResponse response) {
String parameterString = ""
for (String name : response?.headerNames) {
parameterString += "${CR} ${name}=${response?.getHeader(name)}"
}
parameterString
}
}
Could someone please help me figure out how to do this?

Related

Using Restassured how can i select a body as form-type format add Key value pair

I am new to Rest-assured. How can i add Body as data-form and Update the Key and Value pair.
public class RestAssuredRequests {
private static String requestBody = "{\n" +
" \"login\": \"login\",\n" +
" \"email\": \"TEST\",\n" +
" \"pass\": \"ATEST\" \n}";
#BeforeMethod
public static void setup() {
RestAssured.baseURI = "https://TEST/login";
}
#Test
public void postRequest() {
Response response = given()
.body(requestBody)
.when()
.post()
.then()
.extract().response();
System.out.println(response);
//assertEquals(201, response.statusCode());
//assertEquals("foo", response.jsonPath().getString("title"));
//assertEquals("bar", response.jsonPath().getString("body"));
//assertEquals("1", response.jsonPath().getString("userId"));
//assertEquals("101", response.jsonPath().getString("id"));
}
}
You could use multipart method
given().log().all()
.multiPart("login", "login")
.multiPart("email", "TEST")
.multiPart("pass", "ATEST")
.post("https://postman-echo.com/post").prettyPrint();
This is the response
"form": {
"login": "login",
"email": "TEST",
"pass": "ATEST"
}

Return value from Jenkins plugin

I'm developing a Jenkins plugin and in one of my build steps, I need to return a value. In this build step, I'm sending an API call to generate a registration token and I want to return that token as the output of this build step. The idea is to use this generated token later in pipeline/free-style.
My question is, how do I do that?
Here's my Build class:
package **.********.plugins;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.*;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Builder;
import hudson.util.ListBoxModel;
import **.********.constants.Constants;
import **.********.helpers.ApiHelper;
import **.********.helpers.ApiResponse;
import **.********.helpers.LogHelper;
import **.********.model.AgentDockerConfigData;
import **.********.model.AgentDockerConfigGenerationRequestData;
import **.********.model.JobData;
import **.********.model.ProjectData;
import jenkins.tasks.SimpleBuildStep;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
public class GenerateAgentConfigToken extends Builder implements SimpleBuildStep {
//region Private members
private ApiHelper apiHelper;
private String alias;
private String projectId;
private String jobId;
private String browsers;
private AgentDockerConfigData config;
//endregion
//region Constructors
public GenerateAgentConfigToken() { }
#DataBoundConstructor
public GenerateAgentConfigToken(String alias, String projectId, String jobId, String browsers) {
this.alias = alias;
this.projectId = projectId;
this.jobId = jobId;
this.browsers = browsers;
}
//endregion
//region Setters & Getters
public String getAlias() {
return alias;
}
#DataBoundSetter
public void setAlias(String alias) {
this.alias = alias;
}
public String getProjectId() {
return projectId;
}
#DataBoundSetter
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getJobId() {
return jobId;
}
#DataBoundSetter
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getBrowsers() {
return browsers;
}
#DataBoundSetter
public void setBrowsers(String browsers) {
this.browsers = browsers;
}
//endregion
private void init() {
LogHelper.Debug("Initializing API helper...");
this.apiHelper = new ApiHelper(PluginConfiguration.DESCRIPTOR.getApiKey());
}
#Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
#Override
public void perform(#Nonnull Run<?, ?> run, #Nonnull FilePath filePath, #Nonnull Launcher launcher, #Nonnull TaskListener taskListener) throws InterruptedException, IOException {
try {
EnvVars envVars = new EnvVars();
envVars = run.getEnvironment(taskListener);
envVars.put("jobId", jobId);
init();
LogHelper.SetLogger(taskListener.getLogger(), PluginConfiguration.DESCRIPTOR.isVerbose());
generateAgentConfigToken();
} catch (Exception e) {
LogHelper.Error(e);
run.setResult(Result.FAILURE);
}
}
private void generateAgentConfigToken() throws IOException {
LogHelper.Info("Sending a request to generate agent configuration token...");
//TODO: Change the URL to the production URL
ApiResponse<AgentDockerConfigData> response = apiHelper.Post(
Constants.TP_GENERATE_AGENT_CONFIG_TOKEN_URL,
null,
null,
generateRequestBody(),
AgentDockerConfigData.class);
if (response.isSuccessful()) {
if (response.getData() != null) {
config = response.getData();
}
} else {
int statusCode = response.getStatusCode();
String responseMessage = response.getMessage();
String message = "Unable to generate agent configuration token" + (statusCode > 0 ? " - " + statusCode : "") + (responseMessage != null ? " - " + responseMessage : "");
throw new hudson.AbortException(message);
}
}
private AgentDockerConfigGenerationRequestData generateRequestBody() {
// if the user did not provide an alias and jobId, send the body as null
if (StringUtils.isEmpty(alias) && StringUtils.isEmpty(jobId))
return null;
AgentDockerConfigGenerationRequestData body = new AgentDockerConfigGenerationRequestData();
if (!StringUtils.isEmpty(alias))
body.setAlias(alias);
if (!StringUtils.isEmpty(jobId)) {
body.setJobId(jobId);
if (!StringUtils.isEmpty(browsers))
body.setBrowsers(browsers.split(","));
}
return body;
}
#Override
public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); }
#Extension
#Symbol(Constants.TP_GENERATE_AGENT_CONFIG_TOKEN_SYMBOL)
public static class DescriptorImpl extends BuildStepDescriptor<Builder> {
public DescriptorImpl() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req, formData);
}
#Override
public boolean isApplicable(#SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) {
return true;
}
#Nonnull
#Override
public String getDisplayName() {
return Constants.TP_GENERATE_AGENT_CONFIG_TOKEN;
}
public ListBoxModel doFillProjectIdItems() {
HashMap<String, Object> headers = new HashMap<>();
headers.put(Constants.ACCEPT, Constants.APPLICATION_JSON);
ApiResponse<ProjectData[]> response = null;
try {
ApiHelper apiHelper = new ApiHelper(PluginConfiguration.DESCRIPTOR.getApiKey());
response = apiHelper.Get(Constants.TP_RETURN_ACCOUNT_PROJECTS, headers, ProjectData[].class);
if (!response.isSuccessful()) {
int statusCode = response.getStatusCode();
String responseMessage = response.getMessage();
String message = "Unable to fetch the projects list" + (statusCode > 0 ? " - " + statusCode : "") + (responseMessage != null ? " - " + responseMessage : "");
throw new hudson.AbortException(message);
}
ListBoxModel model = new ListBoxModel();
model.add("Select a project", "");
for (ProjectData project : response.getData()) {
model.add(
project.getName() + " [" + project.getId() + "]",
project.getId());
}
return model;
} catch (IOException | NullPointerException e) {
LogHelper.Error(e);
}
return null;
}
public ListBoxModel doFillJobIdItems(#QueryParameter String projectId) {
if (projectId.isEmpty()) {
return new ListBoxModel();
}
HashMap<String, Object> headers = new HashMap<>();
headers.put(Constants.ACCEPT, Constants.APPLICATION_JSON);
ApiResponse<JobData[]> response = null;
try {
ApiHelper apiHelper = new ApiHelper(PluginConfiguration.DESCRIPTOR.getApiKey());
response = apiHelper.Get(String.format(Constants.TP_RETURN_PROJECT_JOBS, projectId), headers, JobData[].class);
if (!response.isSuccessful()) {
int statusCode = response.getStatusCode();
String responseMessage = response.getMessage();
String message = "Unable to fetch the project's jobs list" + (statusCode > 0 ? " - " + statusCode : "") + (responseMessage != null ? " - " + responseMessage : "");
throw new hudson.AbortException(message);
}
ListBoxModel model = new ListBoxModel();
model.add("Select a job to execute from the selected project (You must select a project first)", "");
for (JobData job : response.getData()) {
model.add(
job.getName() + " [" + job.getId() + "]",
job.getId());
}
return model;
} catch (IOException | NullPointerException e) {
LogHelper.Error(e);
}
return null;
}
}
}
Is there a way to return anything from perform rather than void or boolean ?

Flutter response non-json structure form server getting html code

when i connect to server for checking username and password like with this structure
{
"Username":"1",
"Password":"1"
}
i get 0 or 1, without any json format, first letters of username and password are Capital letters, Username,Password,
now i want to get this response with flutter and post http verb
UserInformation class
class UserInformation {
String Username;
String Password;
UserInformation(this.Username, this.Password);
Map<String, dynamic> toJson() {
final Map<String, dynamic> json = new Map<String, dynamic>();
json['Username'] = this.Username;
json['Password'] = this.Password;
return json;
}
}
LoginRepository class:
class LoginRepository {
Future<int> authenticate(
{#required String username, #required String password}) async {
UserInformation userInformation = UserInformation(username, password);
/*this line print {Username: 1, Password: 1}*/
print(userInformation.toJson().toString());
final response = await http.post(
Constants.loginApi, body: userInformation.toJson());
final responseString = jsonDecode(response.body);
if (response.statusCode == 200) {
return responseString;
} else {
throw Exception('fail to get response');
}
}
}
and then this output is response from server:
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Unexpected character (at character 1)
<?xml version="1.0" encoding="utf-8"?>
First: Check for statusCode before accessing response.body. If the call fails, response.body will be an empty String and jsonDecode will fail.
Second: Since you don't get a json formated answer, there is no need to call jsonDecode with the response. final int responseInt = response.body should be enough (maybe you will need int.parse(response.body); needs to be tested.

Get an OAuth2 access token failed with error message "HTTP/1.1 401 Unauthorized"

I am writing OAuth client in JAVA to acquire OAuth token from Central Authentication Service (PingFederate). As this client is standalone utility, there is no application server behind it.
I am trying to achieve : A standalone JAVA client should acquire OAuth token from PingFederate it should allow for some scope, ex. TEST_READ. Once I have access token, I will pass it to resource provider.
So, as per the PingFederate document such standalone client should use the Grant Type=Resource Owner Password Credentials and to acquire Oauth token POST request should contains username/password and client id and secret.
When I attempted the same, I received error in response:
HTTP/1.1 401 Unauthorized [Date: Tue, 28 Aug 2018 09:04:50 GMT, Content-Security-Policy: referrer origin, X-Frame-Options: SAMEORIGIN, Cache-Control: no-cache, no-store, Pragma: no-cache, Expires: Thu, 01 Jan 1970 00:00:00 GMT, Content-Type: application/json;charset=utf-8, WWW-Authenticate: basic realm="PF AS Token Endpoints", Set-Cookie: PF=zVXrZpsAmWwrrVkzgltJZ4;Path=/;Secure;HttpOnly, Transfer-Encoding: chunked] org.apache.http.conn.BasicManagedEntity#68c9133c
To dig more into it, I checked PingFederate audit.log where I found the log: AS| failure| | invalid_client: client_id value doesn't match HTTP Basic username value| 0
Here is my JAVA client code
package com.auth;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.simple.parser.JSONParser;
public class OAuth2Client {
public static final String GRANT_TYPE = "grant_type";
public static final String CLIENT_ID = "client_id";
public static final String CLIENT_SECRET = "client_secret";
private static final String AUTHORIZATION = "Authorization";
public static final String BASIC = "Basic";
public static final String ACCESS_TOKEN = "access_token";
public static final String SCOPE = "scope";
public static void main(String[] args) {
System.out.println(getAccessToken());
}
public static String getAccessToken() {
HttpPost post = new HttpPost(
"https://localhost:9031/as/token.oauth2");
String clientId = "OAUTH-CLIENT-TEST";
String clientSecret = "OAUTH-CLIENT-TEST-SECRET";
String scope = "TEST_READ";
String username = "testuser";
String password = "test#001Pass";
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair(GRANT_TYPE, "password"));
parametersBody.add(new BasicNameValuePair(CLIENT_ID, clientId));
parametersBody.add(new BasicNameValuePair(CLIENT_SECRET, clientSecret));
parametersBody.add(new BasicNameValuePair(SCOPE, scope));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = null;
String accessToken = null;
try {
//post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
post.setEntity(new UrlEncodedFormEntity(parametersBody));
post.addHeader(AUTHORIZATION,
BASIC + " " + encodeCredentials(username, password));
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code >= 400) {
throw new RuntimeException(
"Could not retrieve access token for user: " + username);
}
Map<String, String> map = handleJsonResponse(response);
accessToken = map.get(ACCESS_TOKEN);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return accessToken;
}
public static String encodeCredentials(String username, String password) {
String cred = username + ":" + password;
String encodedValue = null;
byte[] encodedBytes = Base64.encodeBase64(cred.getBytes());
encodedValue = new String(encodedBytes);
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
return encodedValue;
}
public static Map handleJsonResponse(HttpResponse response) {
Map<String, String> responseMap = null;
String contentType = response.getEntity().getContentType().getValue();
try {
responseMap = (Map<String, String>) new JSONParser()
.parse(EntityUtils.toString(response.getEntity()));
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException();
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
throw new RuntimeException();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException();
} catch (RuntimeException e) {
System.out.println("Could not parse JSON response");
throw e;
}
System.out.println();
System.out.println("********** Response Received **********");
for (Map.Entry<String, String> entry : responseMap.entrySet()) {
System.out.println(String.format(" %s = %s", entry.getKey(),
entry.getValue()));
}
return responseMap;
}
}
The grant type "password" requires the user's (or: Resource Owner's) credentials to be passed in the POST parameters (username and password) instead of the Authorization: basic header.

Which Google api to use for getting user's first name, last name, picture, etc?

I have the oauth authorization with google working correctly and am getting data from the contacts api. Now, I want to programmatically get a gmail user's first name, last name and picture. Which google api can i use to get this data?
The contacts API perhaps works, but you have to request permission from the user to access all contacts. If I were a user, that would make me wary of granting the permission (because this essentially gives you permission to spam all my contacts...)
I found the response here to be useful, and only asks for "basic profile information":
Get user info via Google API
I have successfully used this approach, and can confirm it returns the following Json object:
{
"id": "..."
"email": "...",
"verified_email": true,
"name": "....",
"given_name": "...",
"family_name": "...",
"link": "...",
"picture": "...",
"gender": "male",
"locale": "en"
}
Use this code to get firstName and lastName of a google user:
final HttpTransport transport = new NetHttpTransport();
final JsonFactory jsonFactory = new JacksonFactory();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setAudience(Arrays.asList(clientId))
.setIssuer("https://accounts.google.com")
.build();
GoogleIdToken idToken = null;
try {
idToken = verifier.verify(googleAuthenticationPostResponse.getId_token());
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
GoogleIdToken.Payload payload = null;
if (idToken != null) {
payload = idToken.getPayload();
}
String firstName = payload.get("given_name").toString();
String lastName = payload.get("family_name").toString();
If you're using the google javascript API, you can use the new "auth2" API after authenticating to get the user's profile, containing:
name
email
image URL
https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile
For the picture, you can use the Google contacts Data API too: see http://code.google.com/intl/fr/apis/contacts/docs/3.0/developers_guide_protocol.html#retrieving_photo
The simplest way to get this information would be from the Google + API. Specifically the
https://developers.google.com/+/api/latest/people/get
When using the api use the following HTTP GET:
GET https://www.googleapis.com/plus/v1/people/me
This will return all of the above information requested from the user.
I found the answer while looking around in the contacts API forum. When you get the result-feed, just do the following in Java-
String Name = resultFeed.getAuthors().get(0).getName();
String emailId = resultFeed.getId();
I am still looking for a way to get the user profile picture.
Use this Code for Access Google Gmail Login Credential oAuth2 :
Class Name : OAuthHelper
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map.Entry;
import java.util.SortedSet;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.commonshttp.HttpRequestAdapter;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.signature.HmacSha1MessageSigner;
import oauth.signpost.signature.OAuthMessageSigner;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class OAuthHelper {
private static final String TAG = "OAuthHelper";
private OAuthConsumer mConsumer;
private OAuthProvider mProvider;
private String mCallbackUrl;
public OAuthHelper(String consumerKey, String consumerSecret, String scope, String callbackUrl) throws UnsupportedEncodingException {
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
mProvider = new CommonsHttpOAuthProvider("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + URLEncoder.encode(scope, "utf-8"), "https://www.google.com/accounts/OAuthGetAccessToken", "https://www.google.com/accounts/OAuthAuthorizeToken?hd=default");
mProvider.setOAuth10a(true);
mCallbackUrl = (callbackUrl == null ? OAuth.OUT_OF_BAND : callbackUrl);
}
public String getRequestToken() throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
String authUrl = mProvider.retrieveRequestToken(mConsumer, mCallbackUrl);
System.out.println("Gautam AUTH URL : " + authUrl);
return authUrl;
}
public String[] getAccessToken(String verifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException {
mProvider.retrieveAccessToken(mConsumer, verifier);
return new String[] { mConsumer.getToken(), mConsumer.getTokenSecret() };
}
public String[] getToken() {
return new String[] { mConsumer.getToken(), mConsumer.getTokenSecret() };
}
public void setToken(String token, String secret) {
mConsumer.setTokenWithSecret(token, secret);
}
public String getUrlContent(String url) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException {
HttpGet request = new HttpGet(url);
// sign the request
mConsumer.sign(request);
// send the request
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
// get content
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
sb.append(line + NL);
in.close();
System.out.println("gautam INFO : " + sb.toString());
return sb.toString();
}
public String getUserProfile(String t0, String t1, String url) {
try {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(t0, t1);
HttpGet request = new HttpGet(url);
// sign the request
consumer.sign(request);
// send the request
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
//String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
sb.append(line );
in.close();
System.out.println("Gautam Profile : " + sb.toString());
return sb.toString();
} catch (Exception e) {
System.out.println("Error in Geting profile Info : " + e);
return "";
}
}
public String buildXOAuth(String email) {
String url = String.format("https://mail.google.com/mail/b/%s/smtp/", email);
HttpRequestAdapter request = new HttpRequestAdapter(new HttpGet(url));
// Sign the request, the consumer will add any missing parameters
try {
mConsumer.sign(request);
} catch (OAuthMessageSignerException e) {
Log.e(TAG, "failed to sign xoauth http request " + e);
return null;
} catch (OAuthExpectationFailedException e) {
Log.e(TAG, "failed to sign xoauth http request " + e);
return null;
} catch (OAuthCommunicationException e) {
Log.e(TAG, "failed to sign xoauth http request " + e);
return null;
}
HttpParameters params = mConsumer.getRequestParameters();
// Since signpost doesn't put the signature into params,
// we've got to create it again.
OAuthMessageSigner signer = new HmacSha1MessageSigner();
signer.setConsumerSecret(mConsumer.getConsumerSecret());
signer.setTokenSecret(mConsumer.getTokenSecret());
String signature;
try {
signature = signer.sign(request, params);
} catch (OAuthMessageSignerException e) {
Log.e(TAG, "invalid oauth request or parameters " + e);
return null;
}
params.put(OAuth.OAUTH_SIGNATURE, OAuth.percentEncode(signature));
StringBuilder sb = new StringBuilder();
sb.append("GET ");
sb.append(url);
sb.append(" ");
int i = 0;
for (Entry<String, SortedSet<String>> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().first();
int size = entry.getValue().size();
if (size != 1)
Log.d(TAG, "warning: " + key + " has " + size + " values");
if (i++ != 0)
sb.append(",");
sb.append(key);
sb.append("=\"");
sb.append(value);
sb.append("\"");
}
Log.d(TAG, "xoauth encoding " + sb);
Base64 base64 = new Base64();
try {
byte[] buf = base64.encode(sb.toString().getBytes("utf-8"));
return new String(buf, "utf-8");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "invalid string " + sb);
}
return null;
}
}
//===================================
Create : WebViewActivity.class
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends Activity {
//WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);
// Load the page
Intent intent = getIntent();
if (intent.getData() != null) {
webview.loadUrl(intent.getDataString());
}
webview.setWebChromeClient(new WebChromeClient() {
// Show loading progress in activity's title bar.
#Override
public void onProgressChanged(WebView view, int progress) {
setProgress(progress * 100);
}
});
webview.setWebViewClient(new WebViewClient() {
// When start to load page, show url in activity's title bar
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
setTitle(url);
if (url.startsWith("my-activity")) {
Intent result = new Intent();
System.out.println("Gautam my-activity : " + url);
result.putExtra("myurl", url);
setResult(RESULT_OK, result);
finish();
}
}
#Override
public void onPageFinished(WebView view, String url) {
System.out.println("Gautam Page Finish...");
CookieSyncManager.getInstance().sync();
// Get the cookie from cookie jar.
String cookie = CookieManager.getInstance().getCookie(url);
System.out.println("Gautam Cookie : " + cookie);
if (cookie == null) {
return;
}
// Cookie is a string like NAME=VALUE [; NAME=VALUE]
String[] pairs = cookie.split(";");
for (int i = 0; i < pairs.length; ++i) {
String[] parts = pairs[i].split("=", 2);
// If token is found, return it to the calling activity.
System.out.println("Gautam=> "+ parts[0] + " = " + parts[1]);
if (parts.length == 2 && parts[0].equalsIgnoreCase("oauth_token")) {
Intent result = new Intent();
System.out.println("Gautam AUTH : " + parts[1]);
result.putExtra("token", parts[1]);
setResult(RESULT_OK, result);
finish();
}
}
}
});
}
}
//=========================
Call From : MainActivity.class
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.http.HttpResponse;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
Button btnLogin;
OAuthHelper MyOuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
}
#Override
protected void onResume() {
/*System.out.println("On Resume call ");
try {
String[] token = getVerifier();
if (token != null){
String accessToken[] = MyOuthHelper.getAccessToken(token[1]);
}
} catch (Exception e) {
System.out.println("gautam error on Resume : " + e);
}*/
super.onResume();
}
private String[] getVerifier(String url) {
// extract the token if it exists
Uri uri = Uri.parse(url);
if (uri == null) {
return null;
}
String token = uri.getQueryParameter("oauth_token");
String verifier = uri.getQueryParameter("oauth_verifier");
return new String[] { token, verifier };
}
#Override
public void onClick(View v) {
try {
MyOuthHelper = new OAuthHelper("YOUR CLIENT ID", "YOUR SECRET KEY", "https://www.googleapis.com/auth/userinfo.profile", "my-activity://localhost");
} catch (Exception e) {
System.out.println("gautam errorin Class call : " + e);
}
try {
String uri = MyOuthHelper.getRequestToken();
Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
intent.setData(Uri.parse(uri));
startActivityForResult(intent, 0);
/* startActivity(new Intent("android.intent.action.VIEW",
Uri.parse(uri)));*/
} catch (Exception e) {
System.out.println("Gautm Error in getRequestTokan : " + e);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
if (resultCode != RESULT_OK || data == null) {
return;
}
// Get the token.
String url = data.getStringExtra("myurl");
try {
String[] token = getVerifier(url);
if (token != null){
String accessToken[] = MyOuthHelper.getAccessToken(token[1]);
System.out.println("Gautam Final [0] : " + accessToken[0] + " , [1] : " + accessToken[1]);
//https://www.googleapis.com/oauth2/v1/userinfo?alt=json
// String myProfile = MyOuthHelper.getUserProfile(accessToken[0], accessToken[1], "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
String myProfile = MyOuthHelper.getUrlContent("https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
}
} catch (Exception e) {
System.out.println("gautam error on Resume : " + e);
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
//=================================
And Finally Your Profile Information coming, Just Look in your Logcat message print.
Note : Not Forgot to put Internet Permission in Manifest File
And Your App Register in Google Console for Client ID and Secret Key
For App Registration Please Looking this Step : App Registration Step

Resources