woocommerce rest api OAuth authentication in android - android

what is the sample code for OAuth 1.0a(one leg) authentication in android?
is there a library for it? .
I use eclipse and i'm new in android. can anyone clarify the path for me?

to answer my own question:
download Scrib.jar library and add it to your lib folder(you can download it from (here)
create a class with name "OneLeggedApi10" and copy below code in it:
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Verb;
import org.scribe.model.Token;
public class OneLeggedApi10 extends DefaultApi10a {
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return null;
}
#Override
public Verb getAccessTokenVerb() {
return Verb.GET;
}
#Override
public Verb getRequestTokenVerb() {
return Verb.GET;
}
}
now you can do OAuth authentication:
String RESOURCE_URL = "http://yourDomain.com/wc-api/v3/orders";
String SCOPE = "*"; //all permissions
Response response;
OAuthRequest request;
String responsebody = "";
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("your_key")
.apiSecret("your_apiSecret")
.signatureType(SignatureType.QueryString)
.debug()
/*.scope(SCOPE).*/
.build();
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
// Now let's go and ask for a protected resource!
Log.d("scribe","Now we're going to access a protected resource...");
try{
response = request.send();
if (response.isSuccessful()) {
responsebody = response.getBody();
}
} catch (Exception e) {
e.printStackTrace();
}
note that if you are not using above code in an AsyncTask,then put the request.send() part in a thread (actually whole try_catch section) for avoiding run in main thread exception
finally if you want to send data,for example in a case that you want to update an order,replace
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
with these lines:
String payload = yourJsonOBJ.toString();
request = new OAuthRequest(Verb.PUT, RESOURCE_URL);
request.addHeader("Content-Type", "application/json");
request.addPayload(payload);
more information in WooCommerce Documentation site
Hope it help ;)
good luck..

new Thread() {
#Override
public void run() {
String RESOURCE_URL = "http://www.woocommerce.com/wp-json/wc/v1/api/";
String SCOPE = "*"; //all permissions
Response response;
OAuthRequest request;
String responsebody = "";
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("yourConsumerKey")
.apiSecret("yourConsumerSecret")
.signatureType(SignatureType.QueryString)
.debug()
/*.scope(SCOPE).*/
.build();
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
// Now let's go and ask for a protected resource!
Log.d("scribe","Now we're going to access a protected resource...");
try {
response = request.send();
if (response.isSuccessful()) {
responsebody = response.getBody();
Log.v("response", responsebody);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
This code is updated from above, the above code is working getting JSON from wordpress Woocommerce API.
But if you wondering how to use Thread this is the answer.
And I add Log.v for see the json response.

Related

How to send a notification to a distinct user of Android App

I am working on an android app in which client request for a job. When his job is completed I want to send a notification to submit feedback on Android App. Server Api needs to build in laravel and notifications will be send through Firebase. If you have any idea of helping material please share.
I have tried many youtube tutorials but no success. Most of them use custom php apis but i need in laravel and send notification to a specific user.
Thanks!
First of all you need to grab the InstanceToken from the app in the frontend and submit it to your backend somehow.
After you have that you can send notifications from the backend using Firebase. Have a look at this great package for some guidance on how that can be done:
https://firebase-php.readthedocs.io/en/latest/cloud-messaging.html
first of all you get devicetoken from firebase and then send notification from application using this below code.
public class UtilsFcm {
static OkHttpClient mClient;
static Context context;
static JSONArray jsonArray;
public static void sendNotification(final Context context1, final JSONArray jsonArray1) {
mClient = new OkHttpClient();
context = context1;
jsonArray = jsonArray1;
new MyTask().execute();
}
static class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject root = new JSONObject();
JSONObject notification = new JSONObject();
notification.put("text", "Your notification message");
notification.put("title", "App Title");
notification.put("line1", R.mipmap.ic_launcher);
notification.put("line2", "high");
root.put("to", jsonArray.get(i));
root.put("data", notification);
String result = postToFCM(root.toString());
Log.d("Main Activity", "Result: " + result);
return result;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject resultJson = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
static String postToFCM(String bodyString) throws IOException {
final String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
final MediaType JSON
= MediaType.parse("application/json");
RequestBody body = RequestBody.create(JSON, bodyString);
Request request = new Request.Builder()
.url(FCM_MESSAGE_URL)
.post(body)
.addHeader("Authorization", "key=" + "firebase_web_api_key")
.build();
Response response = mClient.newCall(request).execute();
return response.body().string();
}
}
and then you call this method like this.
UtilsFcm.sendNotification(this,jsonArray);
here jsonarray have all device token.
hope this will help you.

Android/OkHttp - client.newCall(request).execute() always return exception

I have to make an android application project. At first, I tried to use HttpURLConnection but it didn't work. So after a discussion with a friend, I tried to use OkHttp. I all time got an exception for "responses = client.newCall(request).execute();". After long hours of searching, I just try this code, which is the tutorial of "https://github.com/square/okhttp/wiki/Recipes"
And..... It doesn't work too !
My question is, what is really happening? I'm currently developping a 4.0.3 application under Android Studio 1.5.1. I also add the two following dependencies:
// DEPENDENCIES
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
// Class Http
public static String run(String url) throws IOException {
try {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodingBuilder()
.add("login", "Mr. X")
.add("password", "********")
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response responses = null;
try {
Log.d("DEBUGG ", "----------------------------------");
responses = client.newCall(request).execute();
Log.d("DEBUGG ", "----------------------------------");
return (responses.body().string());
} catch (IOException e) {
e.printStackTrace();
}
String jsonData = responses.body().string();
JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
}
} catch (JSONException e) {
}
return null;
}
// MainActivity
private TextView textView;
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textViewJSon);
button = (Button)findViewById(R.id.Hit);
textView.setText("Hello !");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
textView.setText(Http.run("https://epitech-api.herokuapp.com/login"));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
{ ANSWER }
I finally tried to use multi-threading programming like said Selvin and it works well So the solution is to open another thread
public static int responseCode = 0;
public static String responseString = "";
public static Thread login = new Thread(new Runnable() {
private OkHttpClient client = new OkHttpClient();
private String url = "https://epitech-api.herokuapp.com/login";
private User user = User.getUser();
public void run() {
try {
// Build the request
RequestBody formBody = new FormEncodingBuilder()
.add("login", user._login)
.add("password", user._password)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response responses = null;
// Reset the response code
responseCode = 0;
// Make the request
responses = client.newCall(request).execute();
if ((responseCode = responses.code()) == 200) {
// Get response
String jsonData = responses.body().string();
// Transform reponse to JSon Object
JSONObject json = new JSONObject(jsonData);
// Use the JSon Object
user._token = json.getString("token");
}
} catch (IOException e) {
responseString = e.toString();
} catch (JSONException e) {
responseString = e.toString();
}
}
});
Most probably, since Honeycomb, network operation in main thread is restricted. So, calling the execute() method is useful when you are already in background thread. But if you are in the main thread then enqueue() will be helpful as it will process the network request in background thread and return the response in main thread. In that case, you just need to pass a callback to get the response.
As you mentioned, using Okhttp is a suggestion from your friend. I also want to recommend you to use Retrofit. It will make your code nicer and maintainable and also handle the threading on behalf of you. Under the hood, it uses Okhttp. More importantly, since version 2.6.0 you can feel the synchronous experience with the help of Coroutines.

HTTP Request POST JSON Object in Body

Hey guys I'm struggeling with HTTP Requests in Java/Android. I want to create a new Github issue. So I've looked it up, and almost everybody did it the same way, but I have the problem that AndroidStudio tells me, that all the classes (HttpClient, HttpPost, ResponseHandler) doesn't exist, did I something wrong or why I don't have them?
private class GithubPostIssues extends AsyncTask<String, Void, String> {
private View view;
public GithubPostIssues(View view) {
this.view = view;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(FeedbackActivity.this, "Feedback/Hilfe gesendet", Toast.LENGTH_SHORT).show();
finish();
}
#Override
protected String doInBackground(String... params) {
return addIssue(view);
}
private String addIssue(View view) {
//here I'm getting some values from the user input and pass them in to the execute method
return execute(title, body, bug, help, question, feature, enhancement, design);
}
private String execute (String title, String body, boolean bug,
boolean help, boolean question, boolean feature,
boolean enhancement, boolean design) {
//Building the JSONOBject to pass in to the Request Body
JSONObject issue = new JSONObject();
JSONArray labels = new JSONArray();
try {
issue.put("title", title);
issue.put("body", body);
labels.put("0 - Backlog");
if (bug) {
labels.put("bug");
}
if (help) {
labels.put("help");
}
if (question) {
labels.put("question");
}
if (feature) {
labels.put("feature");
}
if (enhancement) {
labels.put("enhancement");
}
if (design) {
labels.put("design");
}
issue.put("labels", labels);
return makeRequest("http://requestb.in/uwwzlwuw", issue);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String makeRequest (String uri, JSONObject issue) {
//all these clases aren't found by Android Studio
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(issue));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return httpClient.execute(httpPost, responseHandler);
}
}
Try adding this inside gradle:
android {
useLibrary 'org.apache.http.legacy'

Android-Async-Http Library post error?

I am currently using android-async-http library to send a post/get requests. I didn't have any problem before but now i realize that it gives me timeout error if i send this request without image data. (There is no error if i send exact same request by putting image data as well.)
RequestParams params = new RequestParams();
params.add("mail", mail.getText().toString());
params.add("password", pass.getText().toString());
try {
if (!TextUtils.isEmpty(imagePath))
params.put("image", new File(imagePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(60000);
client.post("some_url", params, myResponseHandler);
What is the reason of this?
Thanks in advance.
After comparing requests and responses, i found out that the case was content-type. With image it was posting multipart, and without it something else.
So i got into RequestParams class in library, and made these changes. Now it works fine. For further troubles i am posting changes that i've made.
I put a flag to determine this request should post as multipart or not:
private boolean shouldUseMultiPart = false;
I created a constructor to set this parameter:
public RequestParams(boolean shouldUseMultiPart) {
this.shouldUseMultiPart = shouldUseMultiPart;
init();
}
And then on getEntity() method i applied these lines:
/**
* Returns an HttpEntity containing all request parameters
*/
public HttpEntity getEntity() {
HttpEntity entity = null;
if (!fileParams.isEmpty()) {
...
} else {
if (shouldUseMultiPart) {
SimpleMultipartEntity multipartEntity = new SimpleMultipartEntity();
// Add string params
for (ConcurrentHashMap.Entry<String, String> entry : urlParams
.entrySet()) {
multipartEntity.addPart(entry.getKey(), entry.getValue());
}
// Add dupe params
for (ConcurrentHashMap.Entry<String, ArrayList<String>> entry : urlParamsWithArray
.entrySet()) {
ArrayList<String> values = entry.getValue();
for (String value : values) {
multipartEntity.addPart(entry.getKey(), value);
}
}
entity = multipartEntity;
} else {
try {
entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return entity;
}

how to parse json response from webservice url and parse it as url in android

I have an application in that i called webservice using this link,I have one webservice Url and another Url is getting as response from that url.I need to use that url as
public static final String TIME_CENTRAL_SERVER = "http://accounts.myexample.com/Services"; in the place of
"http://accounts.myexample.com/Services" i need to parse my json response.
I have check for that in google but couldn't get any answer can anyone help me regarding this, Thanks in advance.
If anyone have queries ask me.
First webservice call is like below
RestClient client = new RestClient(LOGIN_URL);
client.AddParam("accountType", "GOOGLE");
client.AddParam("source", "tboda-widgalytics-0.1");
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);
client.AddParam("service", "analytics");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
After parsing the response, if you want to do another Web Service call, just create another object of RestClient with different URL and Parameters and call execute method, like below,
RestClient client1 = new RestClient(GET_INFO_URL);
client1.AddParam("userid", "123");
try {
client1.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response1 = client1.getResponse();
finally i solved my issue with guidance of my team head below is the code which we have used in constants.java class
public static final String GET_CENTRAL_SERVER = String.format("%s/AccountService/security/ValidateAccess", TIMEMACHINE_ACCOUNTS_SERVER);
and add code snippet in serversync.java class
public String getCentralServer(Context context, String serial_number) throws Exception{
// TODO Auto-generated method stub
WebServiceClient client = new WebServiceClient(Constants.GET_CENTRAL_SERVER);
client.addParam("accesscode", String.valueOf(serial_number));
client.addParam("type", "2");
client.Execute(RequestMethod.GET);
String response = client.getResponse();
if (response != null){
response = response.replaceAll("\\\\/", "/");
response = response.replace("\"", "");
response = response.replace("\n","");
response = "http://" + response;
return response;
}
return null;
}

Categories

Resources