I am trying to add Oauth1 Authorization in my android app using volley
in the postman when i add the details like oauth_consumer_key, oauth_consumer_secret , token_key token_secret like the picture below
it generate a header like below picture and response received successfully.
Postman generated header
Authorization:OAuth oauth_consumer_key="4e77abaec9b6fcda9kjgkjgh44c2e1",oauth_token="2da9439r34104293b1gfhse2feaffca9a1",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1482470443",oauth_nonce="cCbH5b",oauth_version="1.0",oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Problem
I googled a lot to create oauth signature like postmasn created to attach volley ServerConnectionChannel but failed.
oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Current code
public void doSendJsonRequest(final ERequest ERequest) {
requestMethod = String.valueOf(ERequest.method);
requestUrl = String.valueOf(ERequest.mReqUrl);
if(requestMethod.equals(Request.Method.GET)){
requestMethod = "GET";
}else if(requestMethod.equals(Request.Method.POST)){
requestMethod = "POST";
}else if(requestMethod.equals(Request.Method.PUT)){
requestMethod = "PUT";
}else if(requestMethod.equals(Request.Method.DELETE)){
requestMethod = "DELETE";
}
Long tsLong = System.currentTimeMillis()/1000;
final String ts = tsLong.toString();
final String kk = requestMethod+"&" + encode(requestUrl)+"&";
final String kk = encode("GET"+"&"
+ requestUrl+"&"
+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\"&"
+OAUTH_NONCE + "=\"" + getNonce()+ "\"&"
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\"&"
+OAUTH_TIMESTAMP + "=\"" + ts + "\"&"
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\"");
RequestQueue queue = VolleyUtils.getRequestQueue();
try {
JSONObject jsonObject = ERequest.jsonObject;
EJsonRequest myReq = new EJsonRequest(ERequest.method, ERequest.mReqUrl, jsonObject, createReqSuccessListener(ERequest), createReqErrorListener(ERequest)) {
public Map < String, String > getHeaders() throws AuthFailureError {
// Long tsLong = System.currentTimeMillis()/1000;
// String ts = tsLong.toString();
String strHmacSha1 = "";
String oauthStr = "";
strHmacSha1 = generateSignature(kk, oAuthConsumerSecret, oAuthTokenSecret);
strHmacSha1 = toSHA1(strHmacSha1.getBytes());
Log.e("SHA !",strHmacSha1);
oauthStr ="OAuth "+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\","
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\","
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\","
+OAUTH_TIMESTAMP + "=\"" + ts + "\","
+OAUTH_NONCE + "=\"" + getNonce()+ "\","
+OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + "\","
+OAUTH_SIGNATURE + "=\"" + strHmacSha1+ "\"";
Log.e("VALUE OF OAuth str",oauthStr);
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization",oauthStr);
// params.put("Authorization",getConsumer().toString());
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4,
BABTAIN_MAX_RETRIES,
BABTAIN_BACKOFF_MULT));
myReq.setHeader("Cache-Control", "no-cache");
//myReq.setHeader("Content-Type", "application/json");
queue.add(myReq);
} catch (Exception e) {
e.printStackTrace();
}
private String generateSignature(String signatueBaseStr, String oAuthConsumerSecret, String oAuthTokenSecret) {
byte[] byteHMAC = null;
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec spec;
if (null == oAuthTokenSecret) {
String signingKey = encode(oAuthConsumerSecret) + '&';
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
} else {
String signingKey = encode(oAuthConsumerSecret) + '&' + encode(oAuthTokenSecret);
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
}
mac.init(spec);
byteHMAC = mac.doFinal(signatueBaseStr.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
String base64 = Base64.encodeToString(byteHMAC, Base64.DEFAULT);
return base64.trim();
}
private String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
private String byteArrayToHexString(byte[] b) {
String result = "";
for (int i=0; i < b.length; i++)
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
return result;
}
this code create a signature like :oauth_signature="42a611860e29e893a435b555e7a9559a704f4e94" and it failed to get autherization.
getting error like : BasicNetwork.performRequest: Unexpected response code 401 for url
?How to generate oauth_signature like postman provided using volley..
?how can i improve this code ?Is any libraries or default function to do that
?How we add oauth1 signature in volley..
Please Help.. Thank you
I just found a github example for generating signature corresponding to nonce in Oauth1 and successfully integrate into my project
here is the link : https://github.com/rameshvoltella/WoocommerceAndroidOAuth1
Related
try {
final List<NetworkType> dataReceived = getData();
int i = 0;
//Array Iteration
for(final NetworkType networkType : dataReceived) {
i++;
if (i > 3) {
Toast.makeText(getApplicationContext(), "Done!!", Toast.LENGTH_SHORT);
} else {
String mCell1CID = networkType.getCell1CID();
String mCell1LAC = networkType.getCell1LAC();
String mCell1MCC = networkType.getCell1MCC();
String mCell1MNC = networkType.getCell1MNC();
String mCell1CI = networkType.getCell1CI();
String mCell1TAC = networkType.getCell1TAC();
//API requestBody
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyA8NAA3dUpECFn2j6pdcQT3wgqUM98UZ2Q";
String cellID = null;
String locationAreaCode = null;
if (mCell1CID.equals("") && mCell1LAC.equals("")) {
cellID = mCell1CI;
locationAreaCode = mCell1TAC;
} else if (mCell1CI.equals("") && mCell1TAC.equals("")) {
cellID = mCell1CID;
locationAreaCode = mCell1LAC;
} else {
Log.d("GeoL", "3");
}
String requestBody =
"{" +
"\"cellTowers\":[" +
"{" +
"\"cellId\" :" + cellID + "," +
"\"locationAreaCode\" :" + locationAreaCode + "," +
"\"mobileCountryCode\" :" + "\"" + mCell1MCC + "\"" + "," +
"\"mobileNetworkCode\" :" + "\"" + mCell1MNC + "\"" +
"}" +
"]" +
"}";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(String.valueOf(response));
JSONObject latitude = jsonObject.getJSONObject("location");
String lat = latitude.getString("lat");
String lng = latitude.getString("lng");
String acc = jsonObject.getString("accuracy");
if (!dataReceived.listIterator().hasNext()){
String print;
print = String.format("%s%s", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
} else {
String print;
print = String.format("%s%s,", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response", "error" + error.toString());
}
});
queue.add(jsObjRequest);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to concat the received value to the print variable.
But this the error which i receive
print needs to be initialized is what I receive.
also if declared outside the try/catch block it requires it to be final.
What to do?
just use String print = null; when you declare print
You are providing a value that is not initialized to the String.format
You need to initialize the variable "print" with what you want to be used in the String.format (for example an empty String) :
String print= ""
Or use String Builder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("1");
stringBuilder.append("2");
String finalString = stringBuilder.toString();
I've taken over an android app that takes pictures and attaches them to jobs for a larger software system at a company's home base- it has worked fine until recently.
It seems that only on LG G3 phones that have upgraded to Android 6.0 there is an exception in this prodecure:
public static String frapiGetRequest(String transaction, ArrayList<Content> parameters) {
StringBuilder builder = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(HOST,PORT,SCHEME);
String url = SCHEME + "://" + HOST + "/" + transaction;
if (parameters != null && parameters.size() > 0) {
url += "?" + buildParameterString(parameters);
}
Utilities.bLog(TAG, "Making FrapiRequest -- " + url);
try {
HttpGet getRequest = new HttpGet(url);
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(USERNAME, PASSWORD));
/**Exception Occurs Here**/
HttpResponse response = client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = -1;
statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Utilities.bLog(TAG,"Frapi Request Succeeded");
}
else {
Utilities.bLog(TAG, "Frapi Request Failed: " + url);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Utilities.eLog(e);
} catch (IOException e) {
e.printStackTrace();
Utilities.eLog(e);
} catch (Exception e) {
e.printStackTrace();
Utilities.eLog(e);
}
return builder.toString();
}
The stack trace
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at org.apache.http.impl.auth.DigestScheme.isGbaScheme(DigestScheme.java:210)
at org.apache.http.impl.auth.DigestScheme.processChallenge(DigestScheme.java:176)
at org.apache.http.impl.client.DefaultRequestDirector.processChallenges(DefaultRequestDirector.java:1097)
at org.apache.http.impl.client.DefaultRequestDirector.handleResponse(DefaultRequestDirector.java:980)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:490)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at com.rossware.sd_quickpics.Utilities.frapiGetRequest(Utilities.java:111)
at com.rossware.sd_quickpics.Business.authenticate(Business.java:83)
at com.rossware.sd_quickpics.MainActivity$AuthenticateAsyncTask.doInBackground(MainActivity.java:320)
at com.rossware.sd_quickpics.MainActivity$AuthenticateAsyncTask.doInBackground(MainActivity.java:307)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
This hasn't been reported on any other phone.. I would use HttpURLConnection But it doesn't support Digest Authentication (which is currently what our frapi server is using)
I'm just not sure if there's any way to continue using the authentication mechanism we have or if I have to implement a different protocol in frapi (hopefully without breaking all of our existing applications..) or if there is another way to bypass this issue for the folks with these phones? This issue is pretty restricted (one client who has about 10 phones, not the end of the world, but definitely a major issue for them)
Is there anything in android that I can do to resolve this kind of problem for the affected users? Does it seem like the code is incorrect?
It is possible to use DigestAuth with HttpUrlConnection:
private InputStream connect(String urlStr, String username, String password) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) new URL(urlStr).openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
try {
return connection.getInputStream();
} catch(Exception e) {
if (connection.getResponseCode() == 401) {
String header = connection.getHeaderField("WWW-Authenticate");
String uri = new URL(urlStr).getFile();
String nonce = Tools.match(header, "nonce=\"([A-F0-9]+)\"");
String realm = match(header, "realm=\"(.*?)\"");
String qop = match(header, "qop=\"(.*?)\"");
String algorithm = match(header, "algorithm=(.*?),");
String cnonce = generateCNonce();
String ha1 = username + ":" + realm + ":" + password;
String ha1String = md5digestHex(ha1);
String ha2 = "GET" + ":" + uri;
String ha2String = md5digestHex(ha2);
int nc = 1;
String response = ha1String + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2String;
String responseString = md5digestHex(response);
String authorization =
"Digest username=\"" + username + "\"" +
", realm=\"" + realm + "\"" +
", nonce=\"" + nonce + "\"" +
", uri=\"" + uri + "\"" +
", qop=\"" + qop + "\"" +
", nc=\"" + nc + "\"" +
", cnonce=\"" + cnonce + "\"" +
", response=\"" + responseString + "\"" +
", algorithm=\"" + algorithm + "\"";
HttpURLConnection digestAuthConnection = prepareConnection(urlStr);
digestAuthConnection.setRequestMethod("GET");
digestAuthConnection.setRequestProperty("Authorization", authorization);
return processResponse(digestAuthConnection);
} else throw e;
}
}
public static String match(String s, String patternString, boolean strict) {
if (!isEmpty(s) && !isEmpty(patternString)) {
Pattern pattern = Pattern.compile(patternString);
if (pattern != null) {
Matcher matcher = pattern.matcher(s);
if (matcher != null && matcher.find() && (matcher.groupCount() == 1 || !strict)) {
return matcher.group(1);
}
}
}
return null;
}
public static String match(String s, String patternString) {
return match(s, patternString, true);
}
public static byte[] md5Digist(String s) {
try {
MessageDigest md5 = MessageDigest.getInstance("md5");
md5.update(s.getBytes());
return md5.digest();
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String digest2HexString(byte[] digest) {
String digestString="";
int low, hi;
for (int i = 0; i < digest.length; i++) {
low = (digest[i] & 0x0f ) ;
hi = ((digest[i] & 0xf0) >> 4);
digestString += Integer.toHexString(hi);
digestString += Integer.toHexString(low);
}
return digestString;
}
public static String md5digestHex(String s) {
return digest2HexString(md5Digist(s));
}
public static String generateCNonce() {
String s = "";
for (int i = 0; i < 8; i++) {
s += Integer.toHexString(new Random().nextInt(16));
}
return s;
}
I ran into a similar issue today and just started using HttpClient for Android
Added dependency compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1' to build.gradle.
Replace new DefaultHttpClient() with HttpClientBuilder.create().build()
There are probably some other minor refactors you might need to make in other portions of the code, but that should be pretty straight forward.
how to make rest call with key and secret using md5 in android?
but I am getting an error as a response in loginService() method,
error :
{"status":"error","message":"Signature mismatch"}.
the steps I followed,
Step 1- I made a string "param" for getting hash string using md5(string) method
Step 2- called a method loginService() for getting response from web service
Calling code:
{
String param = "name" + first_name + last_name + "email" + email + "facebook_user_id" + facebook_user_id + "location" + location + "zip_code" + zip_code + "birthday" + birthday + "time" + time + "api_key" + api_key;
String signature = md5(param);
Post_Method_Interface commonPost = new CommonPostMethod();
getResponceForParse = commonPost.loginService(
first_name + last_name, email,facebook_user_id, location, zip_code, birthday,time, api_key, signature);
Log.d(">>> GetResponceForParse >>> ",getResponceForParse);
if (!facebook_user_id.equals(null)) {
Post_Method_Interface commonPost = new CommonPostMethod();
getResponceForParse = commonPost
.FacebookLoginModel(first_name + last_name,
email, facebook_user_id, location,
zip_code, birthday, time, api_key,
signature);
Log.d("GetResponceForParse 1", getResponceForParse);
Intent i = new Intent(getApplicationContext(),
HomeActivity.class);
}
loginService() web service method of Post_method_Interface class,
public String loginService(String name, String email,
String facebook_user_id, String location, String zip_code,
String birthday, String timestamp, String api_key, String sig) {
try {
JSONObject schObject = new JSONObject();
schObject.put("name", name);
schObject.put("email", email);
schObject.put("facebook_user_id", facebook_user_id);
schObject.put("location", location);
schObject.put("zip_code", zip_code);
schObject.put("birthday", birthday);
schObject.put("time", timestamp);
schObject.put("api_key", api_key);
schObject.put("sig", sig);
String URL = ApiConstant.URL_FacebookLoginModel;
JsonPostRequest postrequest = new JsonPostRequest();
InputStream is = postrequest.doPost(schObject, URL);
response = postrequest.inputSteamToString(is);
Log.d("Login", response);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return response;
}
md5() method:
private static final String md5(final String parem) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest
.getInstance("MD5");
digest.update(parem.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
Please help me its a very urjent !!!
I have an Android app that posts to a web service via the code below and it all works fine. But the myContract method in the service returns a Boolean, true or false. How do I retrieve that value so I can tell my app to move on or not if false?
HttpPost request = new HttpPost(SERVICE_URI + "/myContract/someString");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Edit
Sorry about the edit, but using HttpResponse, and then logging or toasting response.toString() returns a string I don’t understand!
Update
Thanks Shereef,
But that seems like a bit too much information and code to do what I was trying to do. I have added some code below that works but I’m not sure if it’s right. The service will return a Boolean true or false as to whether or not the POST was successful, but I seem to be retrieving it as a string!
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject jsonResponse = new JSONObject(new String(buffer));
String ServiceResponse = jsonResponse.getString("putCommuniqueResult");
Log.d("WebInvoke", "Saving : " + ServiceResponse);
Is this ok? It works but I’m not sure if its right!
Cheers,
Mike.
private static String getDataFromXML(final String text) {
final String temp = new String(text).split("<")[2].split(">")[1];
final String temp2 = temp.replace("<", "<").replace(">", ">")
.replace("&", "&");
return temp2;
}
/**
* Connects to the web service and returns the pure string returned, NOTE:
* if the generated url is more than 1024 it automatically delegates to
* connectPOST
*
* #param hostName
* : the host name ex: google.com or IP ex:
* 127.0.0.1
* #param webService
* : web service name ex: TestWS
* #param classOrEndPoint
* : file or end point ex: CTest
* #param method
* : method being called ex: TestMethod
* #param parameters
* : Array of {String Key, String Value} ex: { { "Username",
* "admin" }, { "Password", "313233" } }
* #return the trimmed String received from the web service
*
* #author Shereef Marzouk - http://shereef.net
*
*
*/
public static String connectGET(final String hostNameOrIP,
final String webService, final String classOrEndPoint,
final String method, final String[][] parameters) {
String url = "http://" + hostNameOrIP + "/" + webService + "/"
+ classOrEndPoint + "/" + method;
String params = "";
if (null != parameters) {
for (final String[] strings : parameters) {
if (strings.length == 2) {
if (params.length() != 0) {
params += "&";
}
params += strings[0] + "=" + strings[1];
} else {
Log.e(Standards.TAG,
"The array 'parameters' has the wrong dimensions("
+ strings.length + ") in " + method + "("
+ parameters.toString() + ")");
}
}
}
url += "?" + params;
if (url.length() >= 1024) { // The URL will be truncated if it is more
// than 1024
return Communications.connectPOST(hostNameOrIP, webService,
classOrEndPoint, method, parameters);
}
final StringBuffer text = new StringBuffer();
HttpURLConnection conn = null;
InputStreamReader in = null;
BufferedReader buff = null;
try {
final URL page = new URL(url);
conn = (HttpURLConnection) page.openConnection();
conn.connect();
in = new InputStreamReader((InputStream) conn.getContent());
buff = new BufferedReader(in);
String line;
while (null != (line = buff.readLine()) && !"null".equals(line)) {
text.append(line + "\n");
}
} catch (final Exception e) {
Log.e(Standards.TAG,
"Exception while getting " + method + " from " + webService
+ "/" + classOrEndPoint + " with parameters: "
+ params + ", exception: " + e.toString()
+ ", cause: " + e.getCause() + ", message: "
+ e.getMessage());
Standards.stackTracePrint(e.getStackTrace(), method);
return null;
} finally {
if (null != buff) {
try {
buff.close();
} catch (final IOException e1) {
}
buff = null;
}
if (null != in) {
try {
in.close();
} catch (final IOException e1) {
}
in = null;
}
if (null != conn) {
conn.disconnect();
conn = null;
}
}
if (text.length() > 0 && Communications.checkText(text.toString())) {
final String temp = Communications.getDataFromXML(text.toString());
Log.i(Standards.TAG, "Success in " + method + "(" + params
+ ") = " + temp);
return temp;
}
Log.w(Standards.TAG, "Warning: " + method + "(" + params + "), text = "
+ text.toString());
return null;
}
let's say this url makes your service shows it's output
http://google.com/wcfsvc/service.svc/showuserdata/11949
public boolean isWSTrue() {
String data = connectGET("google.com",
"wcfsvc", "service.svc",
"showuserdata/11949", null);
if(null != data && data.length() >0)
return data.toLowerCase().contains("true");
throw new Exception("failed to get webservice data");
}
Note: that within this case you do not actually need to parse the JSON or XML if only checking for boolean then you know if you found true it's true if found anything else it's false.
if you need to get data using XML or JSON you can refer to this answer https://stackoverflow.com/a/3812146/435706
Hey anybody can tell me how can i import all yahoo contacts into my android application please , show me proper way dont give me yahoo api etc if u have source code kindly post it
thank you
just create a layout with webview , and use this code to get contacts.
you need oauth libraries,. and replace consumer key and scret with yours.
public class YahooContacts extends BaseActivity {
private final String TAG = "yahoo_auth";
private static final String CONSUMER_KEY = "you_consumer_key";
private static final String CONSUMER_SECRET = "your_consumer_secret";
private static final String CALLBACK_SCHEME = "http";
private static final String CALLBACK_HOST = "www.blablablao.com";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://"
+ CALLBACK_HOST;
private String AUTH_TOKEN = null;
private String AUTH_TOKEN_SECRET = null;
private String AUTH_URL = null;
private String USER_TOKEN = null;
private String ACCESS_TOKEN = null;
private String ACCESS_TOKEN_SECRET = null;
private String mUSER_GUID = null;
private WebView mWebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yahoo_layout);
mWebview = (WebView) findViewById(R.id.webview);
new getContactsTask().execute();
}
class getContactsTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
getAuthorizationToken();
getUserAutherization();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
private void getAuthorizationToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_request_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&xoauth_lang_pref=en-us"
+ "&oauth_callback=" + CALLBACK_URL;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
AUTH_TOKEN = data[0].replace("oauth_token=", "");
AUTH_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
AUTH_URL = data[3].replace("xoauth_request_auth_url=", "");
VIPLogger.info(TAG, "authToken" + AUTH_TOKEN);
VIPLogger.info(TAG, "authToken secret" + AUTH_TOKEN_SECRET);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getUserAutherization() {
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebViewClient(lWebviewClient);
mWebview.loadUrl("https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token="
+ AUTH_TOKEN);
}
private void getAccessToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ AUTH_TOKEN_SECRET
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&oauth_token="
+ AUTH_TOKEN
+ "&oauth_verifier="
+ USER_TOKEN;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
ACCESS_TOKEN = data[0].replace("oauth_token=", "");
ACCESS_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
mUSER_GUID = data[5].replace("xoauth_yahoo_guid=", "");
VIPLogger.info(TAG, "user guid: " + responseBody);
VIPLogger.info(TAG, "Access token: " + ACCESS_TOKEN);
getAllContacts();
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG,
"error while fetching user guid and access token");
}
}
WebViewClient lWebviewClient = new WebViewClient() {
public void onPageStarted(WebView view, String url,
android.graphics.Bitmap favicon) {
if (url.contains("vipitservice")) {
mWebview.stopLoading();
int lastIndex = url.lastIndexOf("=") + 1;
VIPLogger.info(TAG, url.substring(lastIndex, url.length()));
USER_TOKEN = url.substring(lastIndex, url.length());
mWebview.setVisibility(View.GONE);
getAccessToken();
}
};
};
private void getAllContacts() {
HttpClient httpclient = new DefaultHttpClient();
String host_url = "http://social.yahooapis.com/v1/user/" + mUSER_GUID+ "/contacts";
String nonce = ""+System.currentTimeMillis();
String timeStamp = ""+(System.currentTimeMillis()/1000L);
try{
String params =
""+encode("oauth_consumer_key")+"=" + encode(CONSUMER_KEY)
+ "&"+encode("oauth_nonce")+"="+encode(nonce)
+ "&"+encode("oauth_signature_method")+"="+encode("HMAC-SHA1")
+ "&"+encode("oauth_timestamp")+"="+encode(timeStamp)
+ "&"+encode("oauth_token")+"="+ACCESS_TOKEN
+ "&"+encode("oauth_version")+"="+encode("1.0")
;
String baseString = encode("GET")+"&"+encode(host_url)+"&"+encode(params);
String signingKey = encode(CONSUMER_SECRET)+"&"+encode(ACCESS_TOKEN_SECRET);
VIPLogger.info(TAG, "base string: " + baseString);
String lSignature = computeHmac(baseString, signingKey);
VIPLogger.info(TAG, "signature: " + lSignature);
lSignature = encode(lSignature);
VIPLogger.info(TAG, "signature enacoded: " + lSignature);
String lRequestUrl = host_url
+ "?oauth_consumer_key="+CONSUMER_KEY
+ "&oauth_nonce="+nonce
+ "&oauth_signature_method=HMAC-SHA1"
+ "&oauth_timestamp="+timeStamp
+ "&oauth_token="+ACCESS_TOKEN
+ "&oauth_version=1.0"
+ "&oauth_signature="+lSignature
;
//VIPLogger.info(TAG, lRequestUrl.substring(1202));
HttpGet httpget = new HttpGet(lRequestUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
VIPLogger.info(TAG, "contacts response: " + responseBody);
}catch(Exception e){
e.printStackTrace();
VIPLogger.error(TAG, "error while fetching user contacts");
}
}
public String computeHmac(String baseString, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"),
"HMAC-SHA1");
mac.init(signingKey);
byte[] digest = mac.doFinal(baseString.getBytes());
String result = Base64.encodeToString(digest, Base64.DEFAULT);
return result;
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG, "error while generating sha");
}
return null;
}
public String encodeURIComponent(final String value) {
if (value == null) {
return "";
}
try {
return URLEncoder.encode(value, "utf-8")
// OAuth encodes some characters differently:
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
// This could be done faster with more hand-crafted code.
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String encode(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else {
resultStr.append(ch);
}
}
return resultStr.toString().trim();
}
private char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?#<>#%".indexOf(ch) >= 0;
}
}