In my android application I try to send a json object to a distant server, when I run it I get an error in httpclient.execute(httpPost)
This is a part of my code.
public static String GET(String url , JSONObject js){
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", "Basic **********");
httpPost.setEntity(new StringEntity(js.toString()));
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(httpPost);
} catch (Exception e) {
Log.i("Console", "Error");
}
Any help please.
I guess your Problem is, that you try to run your Network Request from your Main Thread.
I would discourage you to use the Apache HTTP Client at all.
It became deprecated for Marshmallow, see here
Maybe try OkHttp. It offers you the possibility to run a request asynchronously.
Related
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;
}
I have a json parser which is parsing from a url, the app works on WiFi without problems and fast enough but on mobile network it's very slow and most of time not working.
The speed of the mobile network is good enough that whatsapp is working fast, so I don't know if the problem is related to Json parser or http client.
// Async Task to access the web
public String makeHttpRequest(String url, String method,
List<NameValuePair> params) {
HttpParams params1 = new BasicHttpParams();
params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params1);
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return JSON String
return jsonResult;
}
use any third party tools,which have inbuilt features to make your request fast.
AsyncHttpClient :
HTTP requests happen outside the UI thread
Automatic gzip response decoding support for super-fast requests
Retrofit
finally Volley
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster
You can see this information from developer.android.com-training-volley
I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.
I am trying to send data to my server using HttpPost via the following code.
private boolean FacebookLogin(String url) {
boolean isDataSend = false;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data", FacebookData()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String bufstring = EntityUtils.toString(res.getEntity(),
"UTF-8");
isDataSend = true;
}
} catch (Exception e) {
}
return isDataSend;
}
Is there any way i can have a look at how the $_POST looks on the server end. so that it will be easier for me to code the server part.
You can write the received $_POST on a file. Sometimes I do that. It's not the most elegant solution, but it works fine.
Try using a http proxy (e.g. Fiddler) for debugging, it helps a lot in these cases. You can set up an emulator to use this proxy for network communications, so you can inspect the messages sent and received. Check out the emulator docs on how to configure it to use a proxy.
I'm trying to simulate a process like "cache validation" in my application.
I will download a new version of my webapplication on the device (android-based), but I only want to download a new version of the files, based in a etag comparision.
Does anyone a example of how use the Etag mechanism in Android?
You can access the ETag field from a HttpURLConnection object such as like this:
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
String etag = conn.getHeaderField("ETag");
Of course, you will need to make sure that the server you are testing this against supports ETags.
Maybe class "HttpRequest" from this library (kevinsawicki) will help you.
For example:
File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.body(latest);
//Store eTag of response
String eTag = request.eTag();
//Later you can check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
.ifNoneMatch(eTag)
.notModified();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Response:", response.getFirstHeader("etag").toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can refer to the specific implement of ShallowEtagHeaderFilter performing etag generation and validation in Spring.