android okHttp no route to host exception why? - android

I am trying to call http url using okHttp library using the code below:
OkHttpClient client = new OkHttpClient();
Request.Builder builder = new Request.Builder();
builder.url(url);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return e+"";
}
The problem is the url is opened well and return data from browser of device, but when i try to call this function and passing the same url it return
java.net.NoRouteToHostException: No route to host

Related

post request with retrofit gets responce a s bad request in android

I am using https://docs.ngenius-payments.com/reference#hosted-payment-page for payment in android
Headers:
Add these headers to your request (note that you should replace 'your_api_key' with the service account API key in the Getting started section).
Header Value
Content-Type application/vnd.ni-identity.v1+json
Authorization Basic: your_api_key
Body / Form Data:
Add the following information to the form/body content of your request.
Example request (body):
JSON
{
‘realmName’: ‘ni’
}
these are the headers and content type and i created a post method using retrofit
public static Retrofit getRetrofitClient() {
//If condition to ensure we don't create multiple retrofit instances in a single application
if (retrofit == null) {
//Defining the Retrofit using Builder
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //This is the only mandatory call on Builder object.
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
}
return retrofit;
}
My api interface is
#POST("identity/auth/access-token")
Call<NgeniusPaymentAccessTokenModel> nGeniusAccessToken(#Header("content-type") String ContentType, #Header("authorization") String apiKey, #Body JsonObject object);
and i call it by
JsonObject postParam = new JsonObject();
try {
postParam.addProperty("realmName", "ni");
} catch (Exception e) {
e.printStackTrace();
}
Call call = apiService.nGeniusAccessToken(contentType, "Basic "+apiKey, postParam);
i am getting the responce as error telling its a bad request, how to solve this
You can try below code:
String contentType = "application/vnd.ni-identity.v1+json";
String authorization = "Basic: "+apiKey;
JSONObject postParam = new JSONObject();
try {
postParam.put("realmName", "ni");
} catch (JSONException e) {
e.printStackTrace();
}
Call call = apiService.nGeniusAccessToken(contentType, authorization, postParam);
this one worked for me i put all of the headers in a header map
creata a map
Map<String, String> stringMap = new HashMap<>();
try {
stringMap.put("Authorization", "auth");
stringMap.put("Content-Type", "CONTENT_TYPE");
stringMap.put("accept", "accept");
} catch (Exception e) {
e.printStackTrace();
}
api interface looks like
#POST("transactions/orders")
Call<ResponseBody> nCreateOrder(#HeaderMap Map<String, String> headers,String out, #Body JsonObject object);
now call it by
nCreateOrder(stringMap ,"out",jsonObject);

Issue in POST method with Woocommerce REST API

I'm developing an android app with Woocommerce REST API.
I 'm able to access the data's through this REST api using GET method,
now i'm facing issue in creating new customer using this REST API.
here POST method is not working.
my END_POINT is "http:example.com/wp-json/wc/v1/customers"
the problem is am getting authentication error.
I'm using OkHttp for network call.
Here is my code:
protected String doInBackground(Void... params) {
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String authHeader = Credentials.basic(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
Log.e(TAG, "doInBackground: auth -> " + authHeader);
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Accept", "application/json")
.addHeader("Authorization", authHeader)
.build();
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.build();
Response response = client.newCall(request).execute();
return response.message();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "doInBackground: " + e.getLocalizedMessage());
return Tag.IO_EXCEPTION;
}
}
Response message is :
{"code":"woocommerce_rest_cannot_create","message":"Sorry, you are not allowed to create resources.","data":{"status":401}}
i don't know where is an issue is.
If anyone experienced this problem, means please share your solution.
Thanks in advance.

I want to send data to the server and retrieve data from server to device

I am new learner of android app, I want to send data to the server and retrieve data from server to device , how can i do it ? and which server is best? thanks
i think You are asking for send data from android app to web server and received data from web Server.
You can use php in server side and received post Or get method Parameter
and while sending data to Phone use Json.
json is light weighted and easy to parse in android
Search google For RestAPI for Android app using Php
You can use Network library to call server: (In this I used OkHttp3 library)
for request to server:
try {
OkHttpClient okHttpClient = new OkHttpClient();
String url = "url";
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM).addFormDataPart("key", value);
MultipartBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody).build();
Response response = okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
data = response.body().string();
Log.d("msg", "TIcket Data : " + data);
} catch (Exception e) {
e.getStackTrace();
}
Now parse the data which you got from the server: (According to server response whether it's jsonobject or jsonarray or string)
try {
JSONObject jsonObject = new JSONObject(data);
Log.d("msg", jsonObject.toString());
} catch (Exception e) {
e.getStackTrace();
}

How to get data on OkHttp response code 304?

I read that a response with code 304 (Not Modified) should have no body. In that case, does OkHttp get the body from the cache, or shall we get it explicitely, i.e.
if reponseCode == 304:
body = <getDataFromCache>
In the latter case, how to get the data from the cache?
OkHttpClient client = new OkHttpClient();
File cacheDirectory = new File(context.getCacheDir(), "responses");
Cache cache = null;
try {
cache = new Cache(cacheDirectory, 10 * 1024 * 1024); // 10M
client.setCache(cache);
} catch (IOException e) {
Log.e("AbstractFeedIntentService", "Could not create http cache", e);
}
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);
Request request = requestBuilder.build();
Call call = client.newCall(request);
Response response = call.execute();
// if code==304, does the response contain the data from the cache. If not, how to get it?
OkHttp will return data from its response cache.

Problems running deployed apps on Google AppEngine

I have written a web application to run on Google AppEngine using the Restlet framework, communicating using json with web clients. Those work as expected. However, one specific resource written to provide response to an Android client doesn't work when accessed through Android. However, it does work when accessed through a web browser (I do not send the request parameters from the browser and thus get a 400 which is ok in this case).
This code works when running on the DevAppServer:
public class PlayResource extends ServerResource {
private final float SCOREBASE = 1000.0F;
#Get
#Post
public JsonRepresentation play() {
try {
JsonRepresentation rep = new JsonRepresentation(getRequestEntity());
JSONObject inputJson = rep.getJsonObject();
JSONObject outputJson = new JSONObject();
String country = inputJson.optString("country");
outputJson.put("country", doSomething("country",country));
......
......
return new JsonRepresentation(outputJson);
} catch (IOException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_REQUEST));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
} catch (JSONException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_FORMAT));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
}
}
and the client Android device is running this code:
Client client = new Client(Protocol.HTTP);
try {
JsonRepresentation requestJSON = new JsonRepresentation(new JSONObject()
.put("country", country.trim())
);
Request req = new Request(Method.GET,"http://****.appspot.com/resource/play",requestJSON);
Response resp = client.handle(req);
String res = resp.getEntity().getText();
JSONObject resultJSON = new JSONObject(res);
Running this request just hangs the Android client, the server doesn't write any log messages whatsoever suggesting the request doesn't arrive there.
It seems that it's more a Appengine/Java issue than an android issue, but...let's try something else:
instead of using Client and the stuff u are using, first just try to see what the server responds to the simplest connection (as you do in a web browser):
URL url;
try {
url = new URL("http://yourappid.appspot.com/resource/play");
String content = (String) url.getContent();
System.out.println(content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If it works and you get your expeted 400, if so...try to send an httppostrequest with the data...like this:
HttpClient client = new DefaultHttpClient();
HttpUriRequest httpRequest = new HttpPost("http://yourappid.appspot.com/resource/play");
//set the content type to json
httpRequest.setHeader("Content-Type", "application/json");
//get and work with the response
HttpResponse httpResponse = client.execute(httpRequest);
Let me know if the answer was useful

Categories

Resources