ReST API security - android

I am creating an Android App that will communicate with ReST API . And i want to know how do I provide security to the APIs
Here is my sample API method
#GET
#Path("/count")
public String totalUserCount(){
return "100";
}
and here is my call to api from android
StringRequest stringRequesttoNearby = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String responseString) {
//response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
//add request to queue
Singleton.getInstance().getRequestQueue().add(stringRequesttoNearby);
So I want to know how I can add security to this API call

You could use Oauth1.0a, Oauth2 check out the link
Follow link Secure Api

Related

Nested Volley Requests in Android Studio in single session connection

I want to extract data from an HTTPS site. but It's generating an access code for every new opening of the website. so I used volley for getting access code once and getting the result of https once but when I am making 2nd request to get the result, a new session is a creation that leads to a change of access code. Can I do this in a single request ? or is there any alternate way to do this?
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://jntukresults.edu.in/view-results-56736070.html";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
access_code=StringUtils.substringBetween(response, "&accessToken=\"+", ",true);");
Toast.makeText(getApplicationContext(),raju,Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getApplicationContext()).add(stringRequest);
String resultUrl="https://jntukresults.edu.in/results/res.php?ht=16FE1A0593&id=56736070&accessToken="+access_code;
StringRequest stringRequest1=new StringRequest(Request.Method.GET, resultUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
textView.setText(response2);
Toast.makeText(getApplicationContext(),response2,Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getApplicationContext()).add(stringRequest1);

Handle callbacks in my library

I have written an android library that does network calls to various websites and returns the necessary content. I am using Volley library which has callbacks like onResponse and onFailure. Initially this library was an app and was later changed to an library.
When it was an app I could handle the callbacks easily. Whenever the callback happens I call the required functions from there but now when I import as the library and try to use it the control returns from the library as soon as I call it and the call back is not doing anything.
public void sendForVerification(final String Response, final String Secret, final String Name) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
flag = true;
},
new Response.ErrorListener() {
#Override
public void onErrorResponse (VolleyError error){
flag = false;
}
}}) {
#Override
protected Map<String, String> getParams () throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("secret", Secret);
params.put("response", Response);
return params;
}
};
requestQueue.add(stringRequest);
}
}
When this code was a part of the app instead of returning the flag value I would call an appropriate function to handle the result. Now whenever I call these functions the value of flag is returned before the callback is done and this is causing some problem.
My question is how can I warp this around a callback so that the app that uses this library will be notified when the network call is done?
You could add your own callback(s) for your library
interface YourCallback<T> {
onResponse(T value);
}
public void sendForVerification(final String Response,final String Secret,final String Name, YourCallback<Boolean> callback){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onResponse(true);
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onResponse(false);
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params = new HashMap<>();
params.put("secret",Secret);
params.put("response",Response);
return params;
}
};
requestQueue.add(stringRequest);
}
boolean flag;
api.sendForVerification("", "", "", new YourCallback<Boolean>() {
#Override
public void onResponse(Boolean value) {
flag = value;
}
});
Volley is asynchronus, so any other upcoming process after you send the request will continue as normal without waiting for a response. That's why your flag value seems like it hasn't changed, because you probably try to access it while the request is still waiting for a response. That's the reason of callback implementations: you take certain actions as soon as you get a response, and you shouldn't try to handle values that will be returned from another method, because they will be returned before they change.

com.android.volley.AuthFailureError in Android

I am trying to use Google Speech api to translate text from any language to English. There is no error in api connection but
volley
is giving me error.
Thanks for help.
My Activity code:
private void Translate(String s) {
//trim out translate
final String stringToTranslate = s.substring(9);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CONNECTION,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(TO_TRANSLATE, stringToTranslate);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
My PHP Server file, it is in the server and link to this file is provided by URL_CONNECTION Constant
<?php
use Google\Cloud\Translate\TranslateClient;
if($_SERVER['REQUEST_METHOD']=='POST'){
$fb = $_POST['toTranslate'];
require 'vendor/autoload.php';
$translate = new TranslateClient([
'key' => 'My TranslateApi key'
]);
$result = $translate->translate($fb, [
'target' => 'en'
]);
$conversion = $result['text'];
echo $conversion;
}
?>
When i run this activity it toast com.android.volley.AuthFailureError
I googled but i didn't get the relevant answers.
I've had a similar problem. It turned out I was overriding the wrong method to pass parameters. I should send them by the Header, so I changed my code to
"#override public Map<String, String> getHeaders()"
instead of
"#override protected Map<String, String> getParams()"
Maybe it's also your case, you need pass by the header of the message.

How to make use of list of registered users on mysql database to create chat app

Good day, everyone. Please, I really need an answer to this.
I am new to Android development. I am trying to develop an app meant for broadcast messaging. I have been able to create a database where registered users are stored in a table. However, I lack the idea of what to do next.
Most of the tutorials I have seen teach how to make use of users registered on the PARSE platform. But I wonder if I could be able to lift the users on MySQL database and integrate it with any chat client. Thanks.
Check out the Volley library, it's a library made by Google to make requests.
here you have some explications about Volley. You'll need to import volley library in your project.
you have to create the singleton class given by Google (Here called mySingleton) and to create a request class with code like this one :
public class MyRequest {
private Context context;
private RequestQueue queue;
public MyRequest(Context context, RequestQueue queue) {
this.context = context;
this.queue = queue;
}
public void getArticles(final GetArticlesCallback callback){
String url = "YourScriptUrl";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess("I will get this string in the activity");
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onError("erreur : " + error.toString());
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("tag", "postArgument1");
map.put("tag2", "postArgument2");
return map;
}
};
queue.add(request);
}
public interface GetArticlesCallback{
void onSuccess(String success);
void onError(String error);
}
}
And you call this class in your activity :
//queue is a RequestQueue
//request is a Myrequest
queue = VolleySingleton.getInstance(this).getRequestQueue();
request = new MyRequest(this, queue);
request.getArticles(new MyRequest.GetArticlesCallback() {
#Override
public void onSuccess(String success) {
}
#Override
public void onError(String error, String id) {
}
});

Volley Request call URL multiple times

I have recently started on Android development platform. I am using Android Studio, and using Volley library for network operation. I have implemented a backend for push notification for iOS and it is working very well, and now I am triggering this php via Volley network operation as follows.
For some reasons it calls that URL multiple times (5 or 6 times), how do I know? because iOS device receives multiple notifications. I am not sure why this happens and how I could solve it?
public void onClick(View v) {
if(v == buttonBuy) {
message = (EditText) findViewById(R.id.offerText);
buy();
}
}
private void buy()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, Config.ASK_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("token",token);
params.put("pname",objee.optString("pname"));
params.put("toid",objee.optString("uid"));
params.put("pid",pid);
params.put("message",message.getText().toString().trim());
return params;
}
};
CustomVolleyRequest.getInstance(this).getRequestQueue().add(postRequest);
}
Try to add the following code:
int socketTimeout = 10000; //10 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);

Categories

Resources