Android :HttpGet with Params unsuccessful - android

I am using Apache HttpClient, DefaultHttpClient, HttpResponse to make HttpGet Request with JsonObject as request parameter. I receive response in JsonObject format.The Content-Type is application/json
The problem is once a login request fails by providing incorrect login details the next time you correct the details you always fail to get success response.
This scenario doesn't happen if the very first login is successful.
I suspect the params are not going through correctly although I have checked the same. Is there a possibility that the previous request is cached and the new params are not going through.
JSONObject inputBodyObject = new JSONObject();
inputBodyObject.put("email", emailId);
inputBodyObject.put("password", password);
String strURL = this.getString(R.string.base_url) + this.getString(R.string.action_login) + Uri.encode(inputBodyObject.toString());
HttpGet httpGet = new HttpGet(strURL);
httpGet.setHeader("Content-type", "application/json"));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();

Related

HttpContext not holding cookies

I'm trying to use cookies to hold my session on my Android app, but it seems I'm getting something wrong, because I never receive the expected response from my server.
At first I have a login routine that runs as expected and return all expected data.
My login request:
HttpContext httpContext = new BasicHttpContext();
HttpResponse response;
HttpClient client = new DefaultHttpClient();
String url = context.getString(R.string.url_login);
HttpPost connection = new HttpPost(url);
connection.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair(PARAM_LOGIN,params[0]));
nameValuePair.add(new BasicNameValuePair(PARAM_PASSWORD,params[1]));
connection.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
response = client.execute(connection,httpContext);
data = EntityUtils.toString(response.getEntity());
After I've my response I just make what ever I need with the data and then things start to fall a part. Because now I'm just trying to call my server in the same AsyncTask to test if my cookies got properly saved on my HttpContext.
At first I've just called my URL without any change, just reusing my current HttpContext:
HttpPost httpPost = new HttpPost(context.getString(R.string.url_cookie_test));
HttpResponse response = client.execute(httpPost, httpContext);
Since this test fails I tested to add my cookie value on my HttpPost header:
httpPost.addHeader(context.getString(R.string.domain),PHPSESSID+"="+cookieID+";");
Then I tried creating a new HttpContext and force the COOKIE_STORE:
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie(PHPSESSID, cookieID);
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpResponse response;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(context.getString(R.string.url_cookie_test));
response = client.execute(connection,localContext);
All fails, and I've already confirmed that when I first receive my login response I got the data expected from the cookies as can see below:
List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();
for (Cookie cookie: cookies){
Log.i("Cookie Value",cookie.toString());
/*
Prints:[[version: 0][name: PHPSESSID][value: 2ebbr87lsd9077m79n842hdgl3][domain: mydomain.org][path: /][expiry: null]]
*/
}
I've already searched on StackOverflow and I've found a ton of solutions that doesn't really worked for me, will share all solutions I've already tried:
Android: Using Cookies in HTTP Post request
HttpPost request with cookies
Sending cookie with http post android
Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request
As I told you, here you are this piece of code in order to make httpPost to a server developed in Spring MVC, with an API REST. Please, consider to build your request on this way:
Please, pay attention to the comments. You should adapt it to your case ;). You can also enclose this code into a method or whatever you prefer.
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("yourPath");
//NameValuePairs is build with the params for your request
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
CookieStore cookieStore = new BasicCookieStore();
//cookie is a variable that I stored in my shared preferences.
//You have to send in it every request
//In your case, JSESSIONID should change, because it's for Java.
//Maybe it could be "PHPSESSID"
BasicClientCookie c = new BasicClientCookie("JSESSIONID", cookie);
//JSESSIONID: same comment as before.
httppost.setHeader("Cookie", "JSESSIONID="+cookie);
cookieStore.addCookie(c);
((AbstractHttpClient)httpclient).setCookieStore(cookieStore);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
I hope this helps!! It was hard to find it among "old" projects :)

how to send object over Get Request in android

I want to send the below JSON request to a web service and read the response.
{"Email":"aaa#tbbb.com","Password":"123456"}
I know to how to read JSON. The problem is that the above JSON object must be sent in a variable name json.I want to send Json object as a parameter with get request.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpGet httpget = new HttpGet(FinalURL.toString());
//HttpPost request = new HttpPost(serverUrl);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
You can set request using:
httpget.setEntity(new JSONObject(requestString));
One of the options i'm using right now is RequestParams:
It can be implemented as:
RequestParams rp = new RequestParams();
rp.put("Email", "aaa#tbbb.com");
rp.put("Password", "123456");
Utils.client.get(url, rp, new AsyncHttpResponseHandler() {
//or your http code
http://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
http://loopj.com/android-async-http/

Android : call httpget with redirect_uri

I want to make httpget request by android application,
URL = https://www.facebook.com/dialog/oauth?client_id=<number>&redirect_uri=<SOME_URL>&scope=email
Above URL is working fine with browser, It give me proper result on server side, but when I am making http call from application it won't work, got the 200 Response, but it won't give me result.
Code snippet:
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpParams,
CONN_TIMEOUT);
HttpGet httpGet = new HttpGet(URL);
Log.d(TAG,"URL :"+ httpGet.getURI().toURL().toString());
DefaultHttpClient client = new DefaultHttpClient(httpParams);
HttpResponse httpResponse = client.execute(httpGet);
//Log.d(TAG,"httpResponse :" +EntityUtils.toString(httpResponse.getEntity()));
res = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "Response : " + res);
this is because
200 response code "OK"
The request has succeeded. The information returned with the response is dependent on the method used in the request,if there is some result request code will 204

What is wrong with this POST request with json on android?

I'm trying to perform a POST request to a server that wants the Content-Type set to application/json with name and email as some keys. Currently, I'm getting a 406 error, which I'm assuming is working on the server side, but android can't handle the response. How can I tweak the code to get a 200 response?
HttpClient client = new DefaultHttpClient();
HttpEntity entity;
try{
JSONObject j = new JSONObject();
j.put("name" , myName);
j.put("email", myEmail);
HttpPost post = new HttpPost(targetURL);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
entity = response.getEntity();
Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}
Does that look about right? Do I need one of those response handlers when creating the HttpClient?
This works for me with json-2.0.jar
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
HttpResponse response;
ArrayList<appResults> arrayList = new ArrayList<appResults>();
String resul;
try{
HttpGet get = new HttpGet(urls[0]);
response = client.execute(get);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
resul = convertStreamToString(in);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
arrayList = gson.fromJson(resul, listType);
in.close();
of course in asynctask or thread.
But 406... it seems that your format on your webserver and your app are not consistent...

application/soap+msbin1 in android

I just need to send request to webservice via normal HTTP POST inorder to get response.I passed required parameter on body well.While i run it.,i got "Cannot process the message because the content type 'text/json' was not the expected type 'application/soap+msbin1'." error.When i made research over this.,due to "Web Service required the request to have a specific Content-Type, namely "application/soap+msbin1".When i replaced expected content type.,i got Bad Request error.I donno how to recover from that.
My code:
...
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("My URL");
postMethod.setHeader( "Content-Type", "text/json");
postMethod.setHeader( "Cache-Control", "no-cache");
JSONObject json = new JSONObject();
json.put("userName", "My Username");
json.put("password", "My Password");
json.put("isPersistent",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
...
It looks like you are trying to call WCF SOAP service. That service expects correct SOAP communication (= no JSON) and moreover it uses MS binary message encoding of SOAP messages (that is what content type describes) is not interoperable so I doubt you will be able to use it on Android device (unless you find implementation of that encoding for Java / Android).
HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
}
Try using something like this. it worked for me.
Thanks.
N_JOY.

Categories

Resources