Google Book Api access failed on Android - android

Currently I'm working with the Google Books API.
I write a simple request:
public static String request(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
client.getConnectionManager().getSchemeRegistry().register(
new Scheme("SSLSocketFactory", SSLSocketFactory.getSocketFactory(), 443));
HttpGet method = new HttpGet(url);
String data = null;
try
{
BasicHttpResponse response = (BasicHttpResponse) client.execute(method);
data = EntityUtils.toString(response.getEntity());
}
catch (Exception e)
{
System.out.println("IOException in HTTPSRequest.request: " + e.toString());
}
return data;
}
and after that i except a JSonArray:
static final String baseURL = "https://www.googleapis.com/books/v1/volumes?key=" + APIKey + "&q=";
public static String getURL(String searchstring)
{
return baseURL + searchstring;
}
public static JSONObject getJSONObjectFromString(String jsonString)
{
JSONParser parser = new JSONParser();
JSONObject object = null;
try
{
object = (JSONObject) parser.parse(jsonString);
}
catch (Exception e)
{
System.out.println("ParseException in GoogleBooksHelper.getJSONObjectFromString");
}
return object;
}
public static JSONArray getItemsAsJSONArray(String jsonString)
{
JSONObject object = getJSONObjectFromString(jsonString);
JSONArray items = (JSONArray) object.get("items");
return items;
}
But now the Problem, every Time i start a request i get the following:
{"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured"
}
],
"code": 403,
"message": "Access Not Configured"
}
}
But I have no Idea why. In the Api Console I enable the Book api, I have generated a new Api Key with the Project Name.

OK, the Problem for this problem was that i have use the wrong api key, i had it for browser and android, i just copy the key after i test it in the browser. stupid from my side

Related

IOException on HTTP post request

I am creating a login form using Account Manageraccount manager and HTTP task for webservices. when i enter the username and password it gives me IOException, I have added the INTERNET PERMISSION and all the account related permission. If anyone knows any github example which uses account manager and webservices please share the url.please help.this is the code
`
public void userSignUp(String name, String email, String pass, String authType, final SignUPHandler handler) {
HttpPost localHttpPost = new HttpPost(ApiURL.USERSIGNIN);
JSONObject json_user = new JSONObject();
try {
json_user.put("email", email);
json_user.put("password", pass);
StringEntity se = new StringEntity(json_user.toString());
localHttpPost.setEntity(se);
if ((this.currentTask != null) && (this.currentTask.getStatus() != AsyncTask.Status.FINISHED))
this.currentTask.cancel(true);
this.currentTask = new HttpTask(ApiURL.HTTP_LOGIN_HOST, new HttpResponseHandler() {
public void handleException(Exception paramException) {
Log.e("Exceptionssssssss:", "" + paramException);
handler.handleException(paramException);
}
public void handleResponse(JSONObject json)
throws IOException {
Log.d("response", "" + json);
handler.handleResponse(json);
}
});
this.currentTask.execute(new HttpUriRequest[]{localHttpPost});
} catch (Exception localException) {
Log.d("Exception ID", "" + localException.getMessage());
}
}`

Issue creating JSONObject with Instagram API response

I have made a call to the Instagram Endpoint for images that contain the tag #selfie. The issue I am having is in dealing with the response. I get a massive JSON Response, and all I really need is the "thumbnail" image "url".
How can I go about structuring an Object from the Data that is in the JSONObject?
public static class FetchTaggedImages extends AsyncTask<String, Void, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
String mAccessToken = params[0];
String url = (API_URL + "?access_token=" + mAccessToken);
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
String instagramJSONResponse = null;
JSONArray responseArray = null;
HttpResponse postResponse;
try {
postResponse = httpclient.execute(httpGet);
instagramJSONResponse = EntityUtils.toString(postResponse
.getEntity());
JSONObject jsonObject = new JSONObject(instagramJSONResponse);
String thumbnail = jsonObject.getString("url");
responseArray = new JSONArray(instagramJSONResponse);
Log.e("RESPONSE", instagramJSONResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
return responseArray;
}
#Override
protected void onPostExecute(JSONArray response) {
// TODO Auto-generated method stub
super.onPostExecute(response);
Log.e("ONPOSTEXECUTE", "ONPOSTEXECUTE");
JSONObject jsonObject;
}
}
HERE IS A SAMPLE OF THE JSON STRING
{
"data":[
{
"tags":[
"summer",
"love",
"tagstagram",
"colorful",
"instalike",
"selfie",
"swag",
"instago",
"igers",
"follow4follow",
"follow",
"instadaily",
"friends",
"style",
"webstagram",
"look",
"instafollow",
"iphoneonly",
"instagood",
"amazing",
"instacool",
"bestoftheday",
"fun",
"followme",
"like4like",
"picoftheday",
"photooftheday"
],
"location":null,
"link":"http:\/\/instagram.com\/p\/wFlirqPxAW\/",
"user_has_liked":false,
"caption":{
"id":"866263615190011927",
"created_time":"1417486691",
"text":"First contest of the season 🏄",
"from":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"full_name":"Juan Basave"
}
},
"type":"image",
"id":"866263614401482774_507279035",
"likes":{
"data":[
{
"id":"956576929",
"profile_picture":"https:\/\/igcdn-photos-e-a.akamaihd.net\/hphotos-ak-xfa1\/10802992_1561400387426348_1634151041_a.jpg",
"username":"don_assi2014",
"full_name":"-Ali Assi-"
},
{
"id":"520771011",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfa1\/1889350_1565133803717465_1353157813_a.jpg",
"username":"michelle.y6",
"full_name":"Michelle Y"
},
{
"id":"873300277",
"profile_picture":"https:\/\/igcdn-photos-g-a.akamaihd.net\/hphotos-ak-xfa1\/10817804_1543101285933854_123980756_a.jpg",
"username":"ayah_shahbanderr",
"full_name":"Ayah"
},
{
"id":"199966711",
"profile_picture":"https:\/\/igcdn-photos-a-a.akamaihd.net\/hphotos-ak-xfa1\/10617174_587781691338392_1164910966_a.jpg",
"username":"elijah_reissman_",
"full_name":"Elijah Reissman"
}
],
"count":13
},
"images":{
"low_resolution":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_a.jpg",
"height":306,
"width":306
},
"standard_resolution":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_n.jpg",
"height":640,
"width":640
},
"thumbnail":{
"url":"http:\/\/scontent-b.cdninstagram.com\/hphotos-xap1\/t51.2885-15\/1739913_754468237961901_1189124740_s.jpg",
"height":150,
"width":150
}
},
"users_in_photo":[
],
"created_time":"1417486691",
"user":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"bio":"",
"website":"",
"full_name":"Juan Basave"
},
"filter":"Mayfair",
"comments":{
"data":[
{
"id":"866282245801841449",
"created_time":"1417488912",
"text":"#TagStaGram #love #friends #tagstagram #photooftheday #selfie #amazing #followme #follow4follow #like4like #look #instalike #igers #picoftheday #instadaily #instafollow #fun #iphoneonly #instagood #bestoftheday #instacool #instago #summer #follow #webstagram #colorful #style #swag",
"from":{
"id":"507279035",
"profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/profile_507279035_75sq_1397511894.jpg",
"username":"jdbv45",
"full_name":"Juan Basave"
}
}
],
"count":1
},
"attribution":null
},
"thumbnail" is in "images" object, and "images" object is in a first object of the "data" array.
So you need to obtain the "data" JSONArray first, access for each array item, find "images" object from the item, and finally you can access "thumbnail" object.
Your code seems to access to "url" in the top level object that does not have "url" property.
If you'd like to access via JSONObject framework, you should implement the code like this:
public String getUrl(JSONObject response) throws JSONException {
JSONArray data = response.getJSONArray("data");
JSONObject object = data.getJSONObject(0);
JSONObject images = object.getJSONObject("images");
JSONObject thumbnail = images.getJSONObject("thumbnail");
return thumbnail.getString("url");
}
If you need a collection of the url, you need to iterate accessing all data objects like this:
JSONArray data = response.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(0);
// ...
}
This is a basic function for dealing with JSON string that Android Framework provides.
If you feel that it is a long way to go, consider using GSON or Jackson JSON Processor.

send JSON to server via HTTP put request in android

How to wrap given json to string and send it to server via Http put request in android?
This is how my json look like.
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
above is my json array.
below is how I wrote the code but, its not working
protected String doInBackground(Void... params) {
String text = null;
try {
JSONObject child1 = new JSONObject();
try{
child1.put("id", "LED");
child1.put("current_value", "0");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(child1);
JSONObject datastreams = new JSONObject();
datastreams.put("datastreams", jsonArray);
JSONObject version = new JSONObject();
version.put("version", "1.0.0");
version.put("version", datastreams);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPut put = new HttpPut("url");
put.addHeader("X-Apikey","");
StringEntity se = new StringEntity( version.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
put.addHeader("Accept", "application/json");
put.addHeader("Content-type", "application/json");
put.setEntity(se);
try{
HttpResponse response = httpClient.execute(put, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return text;
}
please help on this
this is one sample.
JSONObject Parent = new JSONObject();
JSONArray array = new JSONArray();
for (int i = 0 ; i < datastreamList.size() ; i++)
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", datastreamList.get(i).GetId());
jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
array.put(jsonObj);
}
Parent.put("datastreams", array);
Parent.put("version", version);
and for sending that:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity( Parent.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(se);
client.execute(post);
EDIT
in this sample datastreamList that used in for statement is a list that you must have for all value that want send to server ( one list of one class that have 2 property , id and value ), actually i think you have two class like bellow:
class A {
List<Datastreams> datastreamList
String version;
//get
//set
}
class Datastreams {
String id;
String current_value; // or int
//get
//set
}
and in your code you must have one object of A class that want send to server, so you can use first part to map your object to json.
If you prefer to use a library then I'll prefer you to use Ion Library by Kaush.
Form this library you can simply post your JSON like this :
JsonObject json = new JsonObject();
json.addProperty("foo", "bar");
Ion.with(context, "http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
}
});
Just you have to send as a String so store following JSON data in String
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
then you have to send like:
pairs.add(new BasicNameValuePair("data", finalJsonObject.toString()));
The '{' bracket represent a object and '[' represent an array or list. In your case create a bean
YourObj{
private String version;
private List<DataStream> datastreams;
//getters
//setters
}
DataStream{
private String id;
private String current_value;
//getters
//setters
}
use org.codehaus.jackson:jackson-xc jar for json parssing
use ObjectMapper
String to Object
YourObj obj = new ObjectMapper().readValue(stringyouwanttopass,new TypeReference<YourObj>(){});
now you can use the parsed value.
or you can set the values to the YourObj
YourObj obj =new YourObj();
obj.setVersion(1.0.0);
List<Datastream> datastreams=new ArrayList<Datastream>();
Datastream datestr=new Datastream();
datestr.setId("example");
datestr.setCurrent_value("333");
datastreams.add(datestr);
datestr.setId("key");
datestr.setCurrent_value("value");
datastreams.add(datestr);
datestr.setId("datastream");
datestr.setCurrent_value("1337");
datastreams.add(datestr);
JSONObject jsonget = new JSONObject(appObject);
jsonget.toString();
Connecting server using Jersey
Client client = Client.create();
WebResource webResource = client.resource("serverURl");
ClientResponse response = webResource.path("somePath")
.type("application/json").accept("application/json")
.post(ClientResponse.class, jsonget.toString());
in the server side get it as string and parse it.
here is a android Client library can help you:
Httpzoid - Android REST (JSON) Client,it has some examples and you can do put post,get request easily.
https://github.com/kodart/Httpzoid

Json parsing to fetch nearest gas stations in android

I am parsing a json ,which is a json object to start with.it has an array html_attributions[] and another array results[]
Now as i create the json string from the URL, I can see my json string is coming. But in creating the json object from the json string I am having illegalArugumentException , illegal character in scheme at index 0.
My objective is to find the locations from the json and mark that in my google mapview.
here is my asynctask class..
class LocationJSON extends AsyncTask<String, Integer, Long> {
#Override
protected Long doInBackground(String... arg0) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();String url = jParser.getJSONStringFromUrl("https://maps.googleapis.com/maps/api/place/search/json?location=37.78583400,-122.40641700&radius=1500&types=gas_station&sensor=true&key=AIzaSyBIwW4m6xINOhM_j7hckMAbD3oks_fkLFc");
//main json abject
jsonObject = jParser.getJSONObject(url);
//get to the results array:
try {
JSONArray htmlArray = jsonObject.getJSONArray("html_attributions");
JSONArray resultsArray = jsonObject.getJSONArray("results");
//get to the geometry objects
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject geometry = resultsArray.getJSONObject(i);
//get to the location object
JSONObject location = geometry.getJSONObject("location");
//get to the lat string
double lati = Double.parseDouble(location.getString("Lat"));
double longi = Double.parseDouble(location.getString("lng"));
//create a latlong object
place = new LatLng(lati,longi);
/*//set the map
Marker melbourne = map.addMarker(new MarkerOptions()
.position(place)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//set the camera
cameraUpdate = CameraUpdateFactory.newLatLngZoom(place, 10);
map.animateCamera(cameraUpdate);*/
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//set the map
Marker melbourne = map.addMarker(new MarkerOptions()
.position(place)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//set the camera
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place, 10);
map.animateCamera(cameraUpdate);
}
}
//here is my jsonparser class public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static JSONArray jArray = null;
// constructor
public JSONParser() {
}
public String getJSONStringFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return json;
}
public JSONObject getJSONObject(String url) {
// try parse the string to a JSON object
getJSONStringFromUrl(url);
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser Object",
"Error parsing jsonObject " + e.toString());
}
// return JSON String
return jObj;
}
public JSONArray getJSONArray(String url) {
// try parse the string to a JSON array
getJSONStringFromUrl(url);
try {
jArray = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser Array",
"Error parsing jsonArray " + e.toString());
}
// return JSON String
return jArray;
}
}
here is the json data
{
"html_attributions": [
],
"results": [
{
"geometry": {
"location": {
"lat": 37.7774450,
"lng": -122.4048230
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/gas_station-71.png",
"id": "8e31a915604dd3597225152bfd3ec6f9bfa39395",
"name": "Chevron",
"photos": [
{
"height": 640,
"html_attributions": [
"From a Google User"
],
"photo_reference": "CnRiAAAADAcSOQpR_AW86egDLCWLpuEf00zuXUVFbcxh5-zCY5OzIUtJx764rn2mLnWTMA0xsz3AG7e0ZbU3n_GTJcOI0O15N1Va34GhUMiXirAw6h0DUETlElRwzvNjv1sQoFdimUYCOg-Us4ow9hoeq4cx-RIQSqRYof89YFdoVKRokkHN6RoUT4nJ4eofBuD1pJgwVeIKiaOlVo4",
"width": 480
}
],
"rating": 3.20,
"reference": "CnRkAAAAQ8TbCf9PqmO-_2-vgbFdrKE9j5PIknybR43IdTMziGYAuj5yOW3PcCCfLMgaeEM0ulLWU2WI3-YX14d1bza8tDYAEQlsP4JMTRT1RAeCm_CzhhhcZaB6UZ2Q2_f33iNHxMvoPumNwef6OXXmPQkusxIQ80SUv_R8odDO1dds5ovKZBoURT26TM5W2qKebWGQxfPE0SRgLwQ",
"types": [
"car_repair",
"gas_station",
"establishment"
],
"vicinity": "1000 Harrison Street, San Francisco"
},
],
"status": "OK"
}
-Mahaveer Muttha is right.
Here checkout the Gson Guide
Gson User Guide with tutorial
How I'm parsing google places response to get names of locations:
//data is a String with your JSON
JSONObject jsonObject = new JSONObject(data);
JSONArray googlePlaces = jsonObject.getJSONArray("results");
String[] googlePlacesNames = getStringFromJsonArray(googlePlaces, "name");
private String[] getStringFromJsonArray(JSONArray source, String fieldName){
String result[] = new String[source.length()];
JSONObject json;
try {
for (int i=0; i<source.length();i++) {
json = source.getJSONObject(i);
result[i]=json.getString("name");
Log.d("Places", "Next museum: " + result[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Advice to use GSON for parsing JSON objects is worth attention. By the way, Jackson library could be even better solution for json parsing: http://jackson.codehaus.org/
This way of passing JSON String to Object is more prone to errors. My advice is to use the Spring RestTemplate There you will not have to manipulate the JSON Objects manually. The RestTemplate will get everything done for you when it comes to serializing and desalinizing the JSON String. You will only need to have an entity class which you will have all the fields related to the Gas Stations. You can request a List of Gas Stations even from the RestTemplate. It's a matter of dealing with Java Objects and not this burden of JSON String manipulating manually.
RestTemplate restTemplate = new RestTemplate();
List<GasStation> stations = (List) restTemplate.getForObject(yourURL, List.class);
The above code will get you a list of Gas Stations to your code.

How to parse direct json object only from the json

Here is my JSON link, and how it looks:
{
"to": "CAD",
"rate": 1.0223997600000001,
"from": "USD",
"v": 5.1119988000000003
}
I tried this syntax:
JSONObject o = new JSONObject(sourceString);
String from = o.getString("from");
but it didn't work.
You can create a class
public class Abc {
String to;
String rate;
String from;
String v;
}
and then can use below code for parsing
JsonObject obj= gson.fromJson(DATA,Abc.class);
Where DATA will be your gson string.
Are you running it on simulator?
Or if you are ruuning it on device then off and on your internet connection,it will work.
hello Check this Code it give you result in log(error)
protected void getJSONFromURL(String string) {
// TODO Auto-generated method stub
string = "http://rate-exchange.appspot.com/currency?from=USD&to=CAD&q=5";
String is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet Get = new HttpGet(string);
HttpResponse responce = httpclient.execute(Get);
HttpEntity entity = responce.getEntity();
is = EntityUtils.toString(entity, "UTF-8");
Log.e("responce-->", "" + is.toString());
if (!is.toString().equalsIgnoreCase("")) {
JSONObject ob = new JSONObject(is.toString());
String to = ob.getString("to");
Log.e("to", "" + to);
String from = ob.getString("from");
Log.e("from", "" + from);
double rate = ob.getDouble("rate");
Log.e("rate", "" + rate);
double v = ob.getDouble("v");
Log.e("v", "" + v);
}
} catch (Exception e) {
// TODO: handle exception
Log.d("call http :", e.getMessage().toString());
is = null;
}
}
if you are yseing above 3.0 OS then also include this code;
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT>8){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Your Result is over here:
03-19 11:23:22.745: E/responce-->(811): {"to": "CAD", "rate": 1.0220998400000001, "from": "USD", "v": 5.1104992000000005}
03-19 11:23:22.745: E/to(811): CAD
03-19 11:23:22.776: E/from(811): USD
03-19 11:23:22.776: E/rate(811): 1.02209984
03-19 11:23:22.791: E/v(811): 5.1104992000000005

Categories

Resources