I want to call a web service that requires an authentication cookie.
I have the cookie name and value. but I don't know how to inject the cookie in the request.
can you please provide me with a code sample on how to do this.
Today, i solve the same problem using HttpUrlConnection with this:
CookieManager cookieManager = CookieManager.getInstance();
String cookieString = cookieManager.getCookie(SystemConstants.URL_COOKIE);
URL url = new URL(urlToServer);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Cookie", cookieString);
connection.connect();
OutputStream out = connection.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
If you are using (Http)UrlConnection for the request, then you can use CookieManager to handle cookies. Here is an article on how to use it.
There is no method for adding a cookie to an HttpRequest, but you can set a header or parameter.
Cookies are added to the HttpServletResponse like this:
HttpServletResponse response; //initialized or passed in
Cookie cookie = new Cookie("myname", "myvalue");
response.addCookie(cookie);
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("name", "value");
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpGet = new HttpGet("http://www.domain.com/");
HttpResponse response = httpClient.execute(httpGet, localContext);
You can use droidQuery to handle the request:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.data("data to post")
.cookies($.map($.entry("key", "value"))));
droidQuery also has authentication built in using the standard HTTP authentication approach:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.data("data to post")
.username("myusername")
.password("myPassword"));
Related
I am working with converting website into android app.
Same code work for http URL & I can Re-use same Session id.
But in https I get session expired error.
HttpPost get3 = new HttpPost(titleURL);
entity = new StringEntity("{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"job.order\",\"fields\":[\"job_code\",\"sale_order_id\",\"partner_id\",\"ins_postcode\",\"client_order_ref\",\"cust_po_ref_blanket\",\"engineer_id\",\"appointment\",\"state\"],\"domain\":[[\"state\",\"=\",[\"draft\",\"confirmed\",\"installed\",\"onhold\",\"reject\",\"accepted\"]]],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":1,\"search_default_open_job\":1,\"bin_size\":true},\"offset\":0,\"limit\":80,\"sort\":\"\",\"session_id\":\"3dcfe71efba0403ba454cef4d390f1fb\"},\"id\":\"r105\"}");
get3.setHeader("Content-Type", "application/json");
get3.setHeader("Cookie:","session_id=3dcfe71efba0403ba454cef4d390f1fb");
get3.setEntity(entity);
trustAll();
HttpClient client = new DefaultHttpClient();
responseBody3 = client.execute(get3, responseHandler);
My logcat error,
raise SessionExpiredException(\"Session expired\")\nSessionExpiredException: Session expired\n", "type": "client_exception"}}}
Note: My login URL executes correctly.But I cannot re-use my session id for other URL`s.
any body help me?
I have done this for downloading apk file from https url, you can modify according to your requirement
STEP 1: Created an instance of DefaultHttpClient in the first Activity when connection established.
public static DefaultHttpClient httpClient;
STEP 2: For the first time connection
URL url=new URL(urlToHit);
LoginScreen.httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost);
xr.parse(new InputSource(url.openStream()));
STEP 3: Now for all further connections, used the same httpClient For example in the next activity:
URL url=new URL(urlToHit);
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
xr.parse(new InputSource(instream)); //SAX parsing
get3.setHeader("Cookie:","session_id=3dcfe71efba0403ba454cef4d390f1fb");
That should be
get3.setHeader("Cookie","session_id=3dcfe71efba0403ba454cef4d390f1fb");
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 :)
I used httppost to login a bbs.
The httpclient can save cookie and other information automatically.
I want to get cookie for httpclient and save it.
So next time I can give the cookie to httpclient and I can visit the bbs again.
So my question is how to get cookie from httpclient.
and how to save the cookie.
and how to set httpclient used the cookie.
Thank you.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
BasicCookieStore cookieStore = new BasicCookieStore();
context.setCookieStore(cookieStore);
HttpGet httpget = new HttpGet("https://host/stuff");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
Please note you will need to use the official Apache HttpClient port to Android
Do it like this:
Header[] headers = null;
HttpResponse response = null;
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost post = new HttpPost(URI.create(this._strBaseUrl));
response = httpclient.execute(post);
After request returned, extract cookie via:
headers = response.getHeaders("Set-Cookie");
Then You can iterate through cookie values ( if necessary).
Context: In Android, when I use Java's HttpURLConnection object as shown below, I see the POST body correctly on the server side. However, when I use what I believe is the equivalent HttpClient code, the POST body is empty.
Question:
What am I missing?
Server-side is a Django-python server. I have set up a debug point at the entry point of this endpoint but the post body is already empty. How can I debug through it to find out why the body is null?
Note: I already looked at this , but the solution does not work for me.
Code: using HttpURLConnection - this works:
try {
URL url = new URL("http://10.0.2.2:8000/accounts/signup/");
String charset = "UTF-8";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic base64encodedstring==");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=" + charset);
connection.setDoInput(true);
StringBuilder sb = new StringBuilder();
sb.append("appver=6&user=value1pw=&hash=h1");
OutputStreamWriter outputWriter = new
OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
// handle response
} catch () {
// handle this
}
============================================================
Code: using Apache httpclient - does NOT work - server gets empty POST body:
HttpPost mHttpPost = new HttpPost(""http://10.0.2.2:8000/accounts/signup/"");
mHttpPost.addHeader("Authorization", "Basic base64encodedstring==");
mHttpPost.addHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
mHttpPost.addHeader("Accept-Charset", "UTF-8");
String str = "appver=6&user=value1pw=&hash=h1"; // same as the above
StringEntity strEntity = new StringEntity(str);
mHttpPost.setEntity(strEntity);
HttpUriRequest pHttpUriRequest = mHttpPost;
DefaultHttpClient client = new DefaultHttpClient();
httpResponse = client.execute(pHttpUriRequest);
// more code
I figured the reason why this was happening:
The authorization header in the POST request had an extra new line character "\n" - this was causing the request to go through to the server side handler, but with the body getting cut off. I have never noticed this behavior before.
I am developing server client application on android and i am using session on server side of application but sometimes i lost my session on server.
Ps: i use https connection on server.
I am using these to hold session:
I am using single instance DefaultHttpClient and use it for all http requests.
I use only httpPost method
I use only https certificate:
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
I save my cookies after all http requests:
private void createSessionCookie(){
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (! cookies.isEmpty()){
CookieSyncManager.createInstance(ctx);
CookieManager cookieManager = CookieManager.getInstance();
//sync all the cookies in the httpclient with the webview by generating cookie string
for (Cookie cookie : cookies){
Cookie sessionInfo = cookie;
String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
cookieManager.setCookie(UrlConstants.SERVICE_PRE_URL, cookieString);
CookieSyncManager.getInstance().sync();
}
}
}
Even though i am doing these, i lose session.
Please help me to solve this problem,
Thanks for any advice
Best Regards.
You should not do anything with cookies manually, just create static CookieStore somewhere, assign it to the HttpContext, and use that context in your requests. Cookies will be saved and restored automagically.
These are your class members:
private static CookieStore cookieStore = new BasicCookieStore();
private HttpClient httpclient = new DefaultHttpClient();
private HttpPost post = new HttpPost("your url here");
And this part goes into the member function, which does the request:
HttpContext ctx = new BasicHttpContext();
ctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpResponse result = httpclient.execute(post,ctx);