I am new in BB trying to parse Json file and just want to print the Json responce in a Dialog. But it raises an error regarding No Application Instance and is also getting IllegalStateException. I use GET url method for it.
I Have also add permission in UiApplication like ..
UIApplicationScreen
public static void main(String[] args) {
ApplicationPermissions permRequest = ApplicationPermissionsManager.getInstance().getApplicationPermissions();
permRequest = new ApplicationPermissions();
permRequest.addPermission( ApplicationPermissions.PERMISSION_INTERNET );
ApplicationPermissionsManager.getInstance().invokePermissionsRequest( permRequest );
UiFunApplication app = new UiFunApplication();
app.enterEventDispatcher();
Here is MainScreen Code....
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONArray;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONObject;
public class UiMainscreen extends MainScreen {
public UiMainscreen() {
Dialog.alert("asdasd");
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
// String url = "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
String url = "http://docs.blackberry.com/sampledata.json";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
Dialog.alert("response is ::"+response);
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
}
}
}
Update::
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONArray;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONObject;
public class UiMainscreen extends MainScreen implements FieldChangeListener {
public UiMainscreen() {
ButtonField loginButton;
loginButton = new ButtonField("Go", ButtonField.CONSUME_CLICK);
loginButton.setChangeListener(this);
add(loginButton);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if (field instanceof ButtonField) {
Dialog.alert("Message");
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
// String url =
// "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
String url = "http://docs.blackberry.com/sampledata.json";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
Dialog.alert("response is ::" + response);
/*
* JSONObject resObject = new JSONObject(response); String
* key = resObject.getString("vehicleType");
*
* Vector resultsVector = new Vector(); JSONArray jsonArray
* = resObject.getJSONArray("name"); if (jsonArray.length()
* > 0) { for (int i = 0; i < jsonArray.length();i++) {
* Vector elementsVector = new Vector(); JSONObject jsonObj
* = jsonArray.getJSONObject(i);
* elementsVector.addElement(jsonObj
* .getString("experiencePoints"));
* elementsVector.addElement
* (jsonObj.getString("Insert Json Array Element Key2"));
* resultsVector.addElement(elementsVector); } }
*/
}
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
}
}
}
}
Try this code -
final ButtonField b=new ButtonField("JSON");
add(b);
FieldChangeListener listener=new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(field==b){
try {
String httpURL = "http://docs.blackberry.com/sampledata.json";
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
Dialog.alert(responce);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
b.setChangeListener(listener);
i am developing app in blackberry version 5.0, and i had import all library which require for json in 5.0.
i had download library from this url
http://supportforums.blackberry.com/t5/Java-Development/JSON-library/td-p/573687
even i not getting response, what i had miss in this code please help me.
Below is my code For json parsing.
package mypackage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import JSON_ME_Library.src.org.json.me.JSONArray;
import JSON_ME_Library.src.org.json.me.JSONException;
import JSON_ME_Library.src.org.json.me.JSONObject;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen
{
String url="http://www.appymail.com/iphone-messenger/456842/";
public MyScreen()
{
setTitle("Json Parsing Sample");
String aa=jsonresponse(url);
if(aa.equalsIgnoreCase(""))
{
add(new LabelField("NO res"));
}
else
{
parseJSONResponceInBB(aa);
}
}
void parseJSONResponceInBB(String jsonInStrFormat)
{
try {
JSONObject json = new JSONObject(jsonInStrFormat);
JSONArray jArray= json.getJSONArray("messages");
//JSONArray arr=jArray.getJSONArray(0);
for(int i=0;i<jArray.length();i++)
{
JSONObject j = jArray.getJSONObject(i);
String from = j.getString("id");
add(new LabelField("id=="+from));
String to =j.getString("title");
add(new LabelField("title=="+to));
String message=j.getString("body");
add(new LabelField("Body=="+message));
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
public static String jsonresponse (String url)
{
String response = null;
HttpConnection httpConnection = null;
InputStream inStream = null;
int code;
StringBuffer stringBuffer = new StringBuffer();
try {
httpConnection = (HttpConnection) Connector.open(url, Connector.READ);
httpConnection.setRequestMethod(HttpConnection.GET);
code = httpConnection.getResponseCode();
if(code == HttpConnection.HTTP_OK)
{
inStream=httpConnection.openInputStream();
int c;
while((c=inStream.read())!=-1)
{
stringBuffer.append((char)c);
}
response=stringBuffer.toString();
System.out.println("Response Getting from Server is ================" + response);
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.inform("Connection error");
}
});
}
}
catch (Exception e)
{
System.out.println("caught exception in jsonResponse method"+e.getMessage());
}
finally
{
// if (outputStream != null)
// {
// outputStream.close();
// }
if (inStream != null)
{
try {
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (httpConnection != null )
{
try {
httpConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
}
Hello dear you need to use url extension for blackberry
so please try to change this line
String aa=jsonresponse(url);
as
String aa=jsonresponse(url+";interface=wifi");
After successfully completed download data from url then once check String aa getting any value or not? if it get data then follow
try this if it is working fine then go through this following link
Guide for URL extensions
Enter Url in
String url="Your url";
String request=jsonresponse(url+";interface=wifi");
String response = parseJSONResponceInBB(request);
if(response .equalsIgnoreCase(""))
{
add(new LabelField("NO res"));
}
else
{
add(new LabelField(response ));
}
/* Hi Iam developing an application where the BB app needs to post data to server. The Http connection works fine on Blackberry emulator, but when i try to test it on a real device the application cannot post data to server. the following is my code:
*/
package com.sims.datahandler;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import com.sims.commonmethods.CommonMethods;
import com.sims.screens.MenuScreen;
/**
*
* #author SaiKrishnaPawar
*
*/
public class GPRSHandler extends Thread {
private String data;
private String url;
private String msgKey;
private String mobileNumber;
public String sendGPRSRequest() {
HttpConnection httpConn = null;
DataOutputStream oStrm = null;
DataInputStream is = null;
byte[] resp = null;
String responseData;
try {
// Creating httpconnection object to handle GPRS request
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language", "en-US");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
oStrm = httpConn.openDataOutputStream();
byte dataArray[] = (mobileNumber + "&" + msgKey + data).getBytes();
// byte dataArray[] = (msgKey + data).getBytes();
CommonMethods.getSystemOutput("msg key and data:::"+mobileNumber + msgKey + data);
for (int i = 0; i < dataArray.length; i++) {
oStrm.writeByte(dataArray[i]);
}
DataInputStream din = httpConn.openDataInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = din.read()) != -1) {
baos.write(ch);
}
resp = baos.toByteArray();
responseData = new String(resp);
baos.close();
din.close();
httpConn.close();
return responseData.trim();
} catch (IOException ex) {
CommonMethods.getSystemOutput("IO Exception in run method of gprs handler::" + ex.getMessage());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
int choice = Dialog.ask(Dialog.D_OK, "No Connectivity");
exitApp(choice);
}
});
} catch (NullPointerException nex) {
CommonMethods.getSystemOutput("NullPointerException:" + nex.getMessage());
} catch (SecurityException e) {
CommonMethods.getSystemOutput("SecurityException:" + e.getMessage());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.ask(Dialog.OK, "Security Exception");
UiApplication.getUiApplication().pushScreen(new MenuScreen());
}
});
} finally {
try {
if (is != null) {
is.close();
}
if (oStrm != null) {
oStrm.close();
}
if (httpConn != null) {
httpConn.close();
}
} catch (Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.ask(Dialog.OK, "ERROR in While Connecting GPRS Connection");
UiApplication.getUiApplication().pushScreen(new MenuScreen());
}
});
}
}
return null;
}
public void setData(String data) {
this.data = data;
}
public void setMsgKey(String msgKey) {
this.msgKey = msgKey;
}
public void setUrl(String url) {
this.url = url + ";deviceside=false";
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
private void exitApp(int choice) {
System.exit(0);
}
}
httpConn = (HttpConnection) Connector.open(url);
instead of this you can write//
url = url + ";deviceside=false";
httpConn = (HttpConnection) Connector.open(url);
Please add network extension in this line
httpConn = (HttpConnection) Connector.open(url);
at the end of the url please check did you add url extension
for suppose you are using wifi then you have to add
httpConn = (HttpConnection) Connector.open(url+";interface=wifi");
this is working for interface if you want to other types of networks then just refer my answer here
"Tunnel Failed" exception in BlackBerry Curve 8520
i am trying to get data sending GET request to a php service, but unfortunately i am not getting any result, i am using Blackberry Simulator 9800, here is my code,
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = "";
String url = "http://www.devbrats.com/testing/ActorRated/Service/cities.php";
try{
conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if(conn.getResponseCode() == HttpConnection.HTTP_OK){
in = conn.openInputStream();
//parser.parse(in, handler);
buff.append(IOUtilities.streamToBytes(in));
result = buff.toString();
}
else{
result = "Error in connection";
}
} catch(Exception ex){
ex.printStackTrace();
} finally{
try {
if(in != null){
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Please tell me what is the problem with it,
You will have to use this : http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/io/transport/ConnectionFactory.html
To properly create a network connection with the right parameter.
If you are not using OS5+ use this : http://www.versatilemonkey.com/HttpConnectionFactory.java
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen {
private LabelField lbl;
/**
* Creates a new MyScreen object
*/
public MyScreen() {
setTitle("MyTitle");
new Thread(new ConnectThread(this)).start();
lbl = new LabelField();
this.add(lbl);
}
public void update(Object object) {
synchronized (UiApplication.getEventLock()){
lbl.setText((String)object);
}
}
private class ConnectThread implements Runnable {
private MainScreen screen;
public ConnectThread(MainScreen screen) {
this.screen = screen;
}
public void run() {
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = "";
String url = "http://www.devbrats.com/testing/ActorRated/Service/cities.php";
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
buff.append(IOUtilities.streamToBytes(in));
result = buff.toString();
} else {
result = "Error in connection" + conn.getResponseCode();
}
((MyScreen)screen).update(result);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
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