Hide JSON file from public; only access for my Android app - android

I want to hide my JSON file from the public. So that noone can download this JSON data or go through the browser in my JSON file.
I want only that my own developed app can get the information of this JSON file.
Is there a way to code this? Thanks for answering.

what you need to do is to use token which is only known to your server and your client (mobile app) while making call to your server to get the json data. checkout the following tutorial on how to fetch data from server using token.
android token authentication
retrofit token authentication
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://yourbackend.example.com/tokensignin");
try {
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("idToken", idToken));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
final String responseBody = EntityUtils.toString(response.getEntity());
Log.i(TAG, "Signed in as: " + responseBody);
} catch (ClientProtocolException e) {
Log.e(TAG, "Error sending ID token to backend.", e);
} catch (IOException e) {
Log.e(TAG, "Error sending ID token to backend.", e);
}
Or add a token to retrofit NetworkInterceptor
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", authToken);
}
});
}

Related

How to send an http request to custom api using Oauth 2.0 with AsynceTask

I would like to send an http request to custom api.
I have the request details, and it is working using postman(http client).
Im trying to translate that request to android, using AsyncTask.
I couldnt managed to understand few things:
first, how to send the Bearer token that I have(oauth 2.0).
the second, how to send a jason body.
all the details about the request are in the following link:
https://web.postman.co/collections/7428863-ca5b907d-2752-4d4e-b8a8-29d5cd0dc098?version=latest&workspace=03f5fe5b-0ecd-43f8-8759-3aa868f4cb7f
my "DoInBackground" :
protected Void doInBackground(Void... voids) {
response = null;
Log.v("DoInBackground","entered");
//sending Data
if (valid) {
Log.v("ifvaild","entered");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzcsu4e68qfgi56y7l2qu5ky40da2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer My Bearer"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("script.turn_on", "script.gt1"));
Log.v("nameValue","entered");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
try {
response = httpClient.execute(httpPost);
Log.v("HttpClient","entered");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
this is not working, I get an authentication failure from the server
thanks for your help!
You need to add those pairs in the header. And add the body as entity.
// headers
httpPost.addHeader("Authorization", "Bearer My Bearer");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("script.turn_on", "script.gt1");
// body
String bodyString = "{\"data\":1}"; // your json string
StringEntity bodyEntity = new StringEntity(bodyString);
httpPost.setEntity(bodyEntity);
Just a tip. Look into Retrofit2 library to do all of this.

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed.
Below is my async task background code
HttpClient httpclient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("URL");
String jsonresponse = "";
try {
StringEntity se = new StringEntity(gson.toJson(resultPojo).toString());
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpPut);
HttpEntity httpEntity = response.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
System.out.println("res .... "+jsonresponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
serverside code :
#POST
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response submitUserResponse(#PathParam("userId") int userId,
#PathParam("id") int id, List<ResultPojo> responses) {
try {
//core logic goes here
return Response.status(Response.Status.CREATED).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
Alright just like what was discussed it is most likely a mismatch different HTTP methods, in this case A Put and a post, whenever you ever encounter that HTTP code(405) do perform a validation on the methods you used, it happens.405 errors often arise with the POST method. You may be trying to introduce some kind of input form on the Web site, but not all ISPs allow the POST method necessary to process the form.A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

how to send/POST JWT token from Android to Laravel backend

i wanted to access my back-end using android phone. at this moment i want to do two things:
login the mob app after being authenticated from the Back-end.
Upload data to the back-end (back-end is PHP with Laravel Framework).
i first send email and password to the backend and gotten back a response of JWT token as shown:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cLzE5Mi4xNjguMS4xMDI6ODAwMFwvYXBpXC92M1wvYXV0aGVudGljYXRlIiwiaWF0IjoxNDY2MDA5OTY3LCJleHAiOjE0NjYwMTM1NjcsImp0aSI6IjZjYjBlMTRjYTNkMjAzM2Q4OWM0NzM1M2ZjNjMzZTU2In0.GJGUjgy8U-uqjLSqJcysDTmgrNvxBHH03iBflLjsOwA"
Once the above token returned to the mob app, i want to send the same returned token for further post request, because the above jwt token is my key for accessing the back-end.
So my problem lies on sending the same token back to the back-end. it seems simple and stright forward since i have already started to communicate with my back end, and i have also checked my response by using post man.
and i can also got the user cridential using the jwt token on postman.
now the same token which works on postman is not working for my android. i know that my httpClient and httpPost are working since i have already send the email and password with it. i also know that my android post request is reaching the server since my returned result comes with an error message i built for an accepted token request, as shown below.
as you can see from the above snap shot. i first get the token inside a quotation (first highlighted), when posted for authentication. so i removed the quotation and posted the same token for getting user cridential but this time i got an error response which i built it on the Back-end.
so that is why i think my token is not going to the server properly. but i couldn't fix the problem. but i am guessing the token size is big, with a length of 490. so how shall i attach my token with the httpPost request? my code for the building the request is shown below:
public String getJsonString2(String url, String jwtString) {
String jsonString = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List nameValuePair = new ArrayList(1);
nameValuePair.add(new BasicNameValuePair("token", jwtString));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return jsonString;
}
i have also tried using MultipartEntityBuilder for parsing the parameter (token in my case) but the MultipartEnityBuilder library was crasshing my program when building:
the MultipartEnityBuilder library is added to my project using the following dependencies:
//for accessing the MultipartEntity lbrary
compile "org.apache.httpcomponents:httpcore:4.2.4"
compile "org.apache.httpcomponents:httpmime:4.3"
the error because of the MultipartEntity
So now my question is:
how can i send the jwt token value from android to Laravel backend.
Perhaps try using MultipartEntity instead and create a "part" for the token. I have adapted this closely related answer to your case:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//here you create the token body
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("token", jwtString, ContentType.TEXT_PLAIN);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
I hope this helps, please give it a try and let me know.
You can visit this blog on Multipart Upload with HttpClient and learn more.
i have managed to solve my problem by simply setting the Authorization header with the token:
public String getJsonString2(String url, String jwtString) {
String jsonString = "";
// Creating HTTP client and post
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Authorization", "Bearer \\{" + jwtString + "\\}");
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
System.out.println("Http String content: " + jsonString);
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return jsonString;
}

Google Auth2 giving "invalid_request" response for getting access token & refresh token

How to get the access token & refresh token for google authentication for XMPP. I get successfully the authorization code, but now I need to get the access token & refresh token. But when I do the request in Android with the underneath code I get the response:
{
"error":"invalid_request"
}
HttpPost request = new HttpPost("https://accounts.google.com/o/oauth2/token" );
json.put("client_id", "128232338269.apps.googleusercontent.com" );
json.put("client_secret", "eufZ8Rmjsk1MaADYsHYW" );
json.put("redirect_uri", "urn:ieadsdg:oauth:2.0:oob");
json.put("code", res_code);
json.put("grant_type", "authorization_code");
StringEntity se = new StringEntity(json.toString());
Log.i(TAG, "JSON********" +json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
request.setEntity(se);
/* Checking response */
response = client.execute(request);
but i am getting this error for that code. Response = {
"error" : "invalid_request"
}
what is the problem here. HttpPost method is the correct for this url.
After a chat we found what the problems where. The payload wrong and the content-type was set wrong. The following code is the solution:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("https://accounts.google.com/o/oauth2/token" );
request.setHeader("Content-type", "application/x-www-form-urlencoded");
//Please make this custom with you're credentials
String requestBody = "code=123123132&client_secret=eufFgyAZ8Rmjsk1MaADYsHYW&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code&client_id=128169428269.apps.googleusercontent.com";
try {
request.setEntity(new StringEntity(requestBody));
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
/* Checking response */
try {
HttpResponse response = client.execute(request);
String results = "ERROR";
results = EntityUtils.toString(response.getEntity());
Log.d("STACK", "Response::" + results);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}

Posting a JSONArray to WCF Service from android

I am having trouble posting a JSONArray of values to my WCF Service. When I post the data from Fiddler or .Net Test Client it works fine. Every time I try to post from my android application I get Request Error
This is the JSON data that I send to my WCF Service from the android application. I've tried this exact data from Fiddler and it works
[{"date":"2013-02-22 15:30:374:021","id":"1","description":"test","name":"test"},
"date":"2013-02-25 11:56:926:020","id":"2","description":"ghy","name":"fhh"},
"date":"2013-02-25 11:56:248:026","id":"3","description":"ghfm","name":"run"}]
My android code
public JSONObject makeHttpPost(String url, String method, JSONArray params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type",
"application/json; charset=utf-8");
StringEntity se = new StringEntity(params.toString(),"UTF-8");
se.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(se);
Log.e("Gerhard", params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My WCF Service
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "updateOrderAddress")]
String UpdateOrderAddress(Stream JSONdataStream);
public String UpdateOrderAddress(Stream JSONdataStream)
{
try
{
// Read in our Stream into a string...
StreamReader reader = new StreamReader(JSONdataStream);
string JSONdata = reader.ReadToEnd();
// ..then convert the string into a single "wsOrder" record.
if (JSONdata == null)
{
// Error: Couldn't deserialize our JSON string into a "wsOrder" object.
return "null";
}
return JSONdata; // Success !
}
catch (Exception e)
{
return e.ToString();
}
}
The error I'm getting
02-26 14:00:56.185: E/Gerhard(31064): <p>The server encountered an error processing the request. The exception message is 'Incoming message for operation 'UpdateOrderAddress' (contract 'IService1' with namespace 'http://tempuri.org/') contains an unrecognized http body format value 'Json'. The expected body format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details. The exception stack trace is: </p>
I have called multiple GET requests from android application to same WCF Service and it works great, but now I need to send an array of data to the wcf service. Please please help me.Thanks in advance
remove
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
from ur code

Categories

Resources