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).
Related
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();
I'm pretty new in the Android world and maybe my question is very simple..
I have an android app where I use HttpGet to connect to a server and collect data.
However the server sometimes sets some cookies that are not remembered by my code.
I found a post where its using a custom cookie policy and is accepting everything.. just what I need.But I cant implement it.As I understand my version of java httpclient is old and does not have the functions I need.
Here's my code:
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(link);
get.getParams().setParameter(
ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
HttpResponse responseGet = client.execute(get,ctx);
status_code = responseGet.getStatusLine().getStatusCode();
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
http_response = EntityUtils.toString(resEntityGet);
}
}
And the code I need to implement:
CookieStore cookieStore = new BasicCookieStore();
httpclient.setCookieStore(cookieStore);
CookieSpecFactory csf = new CookieSpecFactory() {
public CookieSpec newInstance(HttpParams params) {
return new BrowserCompatSpec() {
#Override
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
log.debug("allow all cookies");
}
};
}
};
httpclient.getCookieSpecs().register("easy", csf);
httpclient.getParams().setParameter(
ClientPNames.COOKIE_POLICY, "easy");
All I need is to set this csf policy to my client.
However it seems that I dont have these two functions in the library : setCookieStore and getCookieSpecs().register()
What are my options to run it ?!
I am trying to do http digest authentication from an android client. Here is a curl line that connects and does the digest successfully.
curl -i --digest --user 'c#c.com:500a436e-2d5d-4a2e-be82-19651f7ea904' -v https://localhost:8080/v1/resources/debug
Here is one attempt in my android client that returns a 401.
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("user agent");
String url = "http://localhost:8080/v1/resources/debug";
URL urlObj = new URL(url);
HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("c#c.com", "500a436e-2d5d-4a2e-be82-19651f7ea904");
CredentialsProvider cp = new BasicCredentialsProvider();
cp.setCredentials(scope, creds);
HttpContext credContext = new BasicHttpContext();
credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);
HttpGet job = new HttpGet(url);
HttpResponse response = httpClient.execute(host,job,credContext);
StatusLine status = response.getStatusLine();
System.out.println("#### " + status.toString());
httpClient.close();
Here is a second attempt in the client, also returns a 401.
DefaultHttpClient httpclient = new DefaultHttpClient();
DefaultHttpClient httpclient2 = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://localhost:8080/v1/resources/debug");
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
System.out.println("authHeader = " + authHeader);
DigestScheme digestScheme = new DigestScheme();
digestScheme.processChallenge(authHeader);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("c#c.com", "500a436e-2d5d-4a2e-be82-19651f7ea904
httpget.addHeader(digestScheme.authenticate(creds, httpget));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient2.execute(httpget, responseHandler);
System.out.println("responseBody : " + responseBody);
}
Can anyone see what I'm missing to get the authentication to work? We know it's not a server problem since the curl line works great.
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 do you do write an HttpPut request with authentication on Android?
(I'm trying to work around using HttpURLConnection, which seems to serious have bugs (at least in Android 2.2) but GET works fine. I'd like to send a JSON representation of an array, and I have correct credentials already set using PasswordAuthentication.)
First you need to have an authentication token. And then just add this line.
httpGet.setHeader("Authorization", "Bearer " + yourToken);
Here's one general solution.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, this.CONNECT_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, this.CONNECT_TIMEOUT);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
// Retrieve user credentials.
SharedPreferences settings = context.getSharedPreferences("LOGIN", 0);
String loginNameString = settings.getString("login_name", null);
String passwordString = settings.getString("password", null);
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(loginNameString, passwordString);
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
client.getCredentialsProvider().setCredentials(authScope,
credentials);
HttpPut put = new HttpPut(UPLOAD_URL);
try
{
put.setEntity(new StringEntity(responseJSONArray.toString(),
SERVER_PREFERRED_ENCODING));
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
HttpResponse response = client.execute(put);
// 200 type response.
if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK &&
response.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES)
{
// Handle OK response etc........
}
}
catch (Exception e)
{
}