I am having a strange problem while using Apache HttpClient in an Android app.
My app needs to Login to a website and get some data and then logout.
My current code looks like this:
public class BlueClient {
private String hostUrl;
private DefaultHttpClient client;
private HttpContext localContext;
public BlueClient(String hostUrl,DefaultHttpClient httpClient,HttpContext localContext) {
this.hostUrl = hostUrl;
this.client = httpClient;
this.localContext = localContext;
}
public boolean doLogin(String userName,String password){
String url = getHostUrl()+"do_login";//loggin will set a session cookie
HttpPost post = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",userName));
nameValuePairs.add(new BasicNameValuePair("password",password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post,localContext);
//ok now if response is ok then return true
} catch (Exception e) {
}
return false;
}
public MyStuff getMyStuff(){
String url = getHostUrl()+"/getMyStuff/"; //this url requires authentication. the sesion cookie should do that
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get,localContext);
//ok get my stuff from response and return
} catch (Exception e) {
}
return null;
}
public boolean doLogout(){
String url = getHostUrl()+"do_logout";//it clears the cookie so the session is invalidated
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get,localContext);
//ok the cookie is cleared
}
} catch (Exception e) {
}
return false;
}
}
And when i call these function i do like this. It works in emulator but not in device
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
context.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
DefaultHttpClient httpClient = new DefaultHttpClient();
BlueClient myClient = new BlueClient("http://myHost.com/",httpClient,context);
myClient.doLogin("user","pass");
// it should've printed the cookies set by the server but i get nothing here !
D.log(context.getAttribute(ClientContext.COOKIE_STORE));
// as this is another subsequesnt request it shoud carry the cookies back to the server but as the cookies are not set this function gives me nothig :-(
myClient.getMyStuff();
myClient.doLogout();
Can anyone please shed some light on this. Why its not working in the device?
Ah I finally found the problem!
My server runs on CodeIgniter. And CodeIgniter set the expiry date of the session cookie (ci_session) as Netscape cookie draft compliant. And the format is EEE, dd-MMM-yy HH:mm:ss zzz and Default CookiePoicy used by HttpClient is RFC_2109. So when the httpClient tries to parse the cookie data it fails on parsing the expiry date. I had to explicitly set the Cookie Policy and date format.
So my final code looks like this:
BasicHttpParams params = new BasicHttpParams();
String[] dateFormats = {"EEE, dd-MMM-yy HH:mm:ss zzz"};
params.setParameter(CookieSpecPNames.DATE_PATTERNS,Arrays.asList(dateFormats));
DefaultHttpClient httpClient = new DefaultHttpClient(params);
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.NETSCAPE);//explicitly set the cookie policy
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
context.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
BlueClient myClient = new BlueClient("http://myHost.com/",httpClient,context);
myClient.doLogin("user","pass");
myClient.getMyStuff();//now i get my stuff !
myClient.doLogout();
Hope it saves someone's time :)
Related
I am calling a restful api using HttpClient 4.4.1, but it is not sending the cookies,
private CloseableHttpResponse call(String url, javax.servlet.http.HttpServletRequest httpServletRequest) {
HttpGet request = new HttpGet(url);
BasicHttpContext localContext = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
javax.servlet.http.Cookie[] cookies = httpServletRequest.getCookies();
BasicClientCookie basicClientCookie = null;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
javax.servlet.http.Cookie cookie = cookies[i];
basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
basicClientCookie.setDomain(cookie.getDomain());
basicClientCookie.setPath("/");
basicClientCookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
basicClientCookie.setVersion(0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 100);
Date date = calendar.getTime();
basicClientCookie.setExpiryDate(date);
cookieStore.addCookie(basicClientCookie);
}
}
if (cookieStore.getCookies() != null) {
System.out.println("Cookies size " + cookieStore.getCookies().size());
}
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(request, localContext);
} catch (IOException e) {
System.out.println("msg " + e.getMessage());
}
return httpResponse;
}
I can see it is only sending the last cookie which has been added. What am i missing? Please help.
The problem is for sure in the code inside the for loop because only the last added cookie is visible.
Try to debug the for loop either using debugger or by adding the system.out.println statement before the loop when you are getting cookies array from request, than inside the loop when you are creating basic client cookie and then before and after adding basic client cookie to cookiestore
As suggested in the comments you have also not added cookiestore to the context.
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
Another problem with the above code is
basicClientCookie.setDomain(cookie.getDomain());
cookie.getDomain() and url of the request can be different and as per the cookies behaviour they should be same then only cookies will send.So only cookies having same url will be send with the request
This question already has answers here:
HTTP POST using JSON in Java
(12 answers)
Sending a JSON HTTP POST request from Android
(2 answers)
Closed 5 years ago.
hi im new to AsyncTask and i need to send data to API server. im doing the connection and im stuck here. i read about the AsyncTask and this is the code that i've seen. first thing is if i determine if the device is connected, it will send data on the URL given, else. it will send thru SMS
public class SendData extends AsyncTask <String, Void, Boolean> {
DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
Date date = new Date();
String datefinal = dateFormat.format(date).toString();
String url = "http://192.168.1.212/mobile_alerts_api.php?location=&msg=&datetime=&id=";
#Override
protected Boolean doInBackground(String... urls) {
try{
HttpGet httppost = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
}
}
Use:
HttpPost httppost = new HttpPost(url);
instead of
HttpGet httppost = new HttpGet(url);
Get is used to get data from the server. Post is used to send data to the server
String json=yourJsonData;
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
Then execute the httppost in your async task class
In my app I've a first activity that allow you to login to a web service. If the server allow user to connect it should call a TabHost activity. In TabHost activity I've 3 different activity:
HomeActivity: it display just a webview
HistoryActivity: it should display a ListView in which I insert the notification history
SettingsActivity: it display some settings of the app
In HistoryActivity I've to call to a web service to download a list of the notification history. To call this service I've to keep user logged, how I can do that?
I'm using the following code to connect to history service:
public void postData(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
StringEntity jsonSend = new StringEntity("{\"history\": true}");
httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
httpPost.setEntity(jsonSend);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
Log.d("HISTORY", json);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I used it for login and it works great. To connect to login service I use the following code:
public void postData(final String username, final String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("pollingId", "XXXXXXXXX"));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
JSONObject jsonObject = new JSONObject(json);
Boolean success = jsonObject.getBoolean("success");
if (success == true) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "ACCESSO EFFETTUATO!", Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this, TabBarActivity.class);
startActivity(i);
}
});
}
} catch (ClientProtocolException e) {
Log.d("CLIENT EXCEPTION", "ERRORE: " + e);
}catch (IOException e) {
Log.d("I/O EXCEPTION", "ERRORE: " + e);
} catch (JSONException e) {
e.printStackTrace();
}
}
If I use it to get notification history the JSON said me that user is not logged. How I can fix it? Thank you
UPDATE
I tried to follow your suggestions, but I've the same result. The modified code is the follow:
MainActivity.java
public void postData(final String username, final String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://extranet.gruppotesta.it/srv/at-brain/login.jsp");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("pollingId", "XXXXXXX"));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
JSONObject jsonObject = new JSONObject(json);
Boolean success = jsonObject.getBoolean("success");
if (success == true) {
Header[] cookie = response.getHeaders("cookie");
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", cookie.toString());
editor.commit();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "ACCESSO EFFETTUATO!", Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this, TabBarActivity.class);
startActivity(i);
}
});
}
} catch (ClientProtocolException e) {
Log.d("CLIENT EXCEPTION", "ERRORE: " + e);
}catch (IOException e) {
Log.d("I/O EXCEPTION", "ERRORE: " + e);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
HistoryActivity.java
public void postData(String url) {
HttpClient httpClient = new DefaultHttpClient();
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String stringCookie = sharedPreferences.getString("cookie", null);
BasicCookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("login", stringCookie);
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httpPost = new HttpPost(url);
try {
StringEntity jsonRequest = new StringEntity("{\"history\": true}");
httpPost.setEntity(jsonRequest);
httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
httpPost.setHeader("Cookie", cookie.toString());
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String json = builder.toString();
Log.d("HISTORY", json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I try to run the app the server answer me with error "User not logged". What's wrong in my code?
When you first login, the web service must provide you with some sort of access token - a valid user id perhaps. You need to store and retrieve this user id in a SharedPreference. This user id must be passed as a parameter to all subsequent web services to indicate that the user is indeed logged in.
The official tutorial for how to get and set a SharedPreference is here.
You can try to use CookieStore to store a cookie with the login credentials. Take a look at this link: Http cookie store in Android.
Does your service give back a session cookie after successful login? If so you should store the cookie that the service issues after a login (in the Set-Cookie header in the response from the server) and set this cookie for any future HTTP requests.
httpPost.setHeader("Cookie", COOKIE_FROM_SERVER_AFTER_LOGIN);
You could use a CookieStore as well to help you store the cookies from HTTP requests - this will make cookie and session management easier.
UPDATE
Server headers won't include a Cookie header but a Set-Cookie header (because the server is instructing your useragent/browser/client to set a cookie and it's this cookie that will be included in your Cookie headers) so change this line:
response.getHeaders("cookie");
to
response.getHeaders("set-cookie");
UPDATE:
Your revision is now pulling out the correct Set-Cookie header but you are incorrectly storing the value (you are storing the entire header as the cookie when all you need is the value).
if (success == true) {
Header[] cookies = response.getHeaders("set-cookie");
//at this point cookies looks like this:
//Set-Cookie: JSESSIONID=84DB43CE8CABC52EBDF777BC0EA96D0F; Path=/; Secure
//if you just do cookies.toString() like you were doing before it will also include
//the cookie header which will create an incorrect cookie value.
//you just need the value of the Set-Cookie header and store that as your cookie
if (cookies.length > 0){
//it is very possible for a server to return more than one Set-Cookie header so the proper
//way would be to iterate through all of the values and string them together
//in the correct synatax of
//so you might want to store all of the values as a list in sharedPreferences
//and let your cookie store put them all in the request for you
String finalCookie = "";
for (Header header: cookies){
//access the value from the Header object and nothing else
//JSESSIONID=90D84EF5D5BD1C4008F332F9EDA8F9AA; Path=/; Secure;
if (header.getValue().contains(";")){
finalCookie += String.format("%s; ", header.getValue().split(";")[0]);
} else {
finalCookie += String.format("%s; ", header.getValue());
}
}
//finalCookie = JSESSIONID=1B70CAB822430E14991E14ACAE153F5D;
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie", finalCookie);
editor.commit();
}
Now in your StoredPreferences you will have correctly formatted cookies (in your case you are only returning one from your server but it's likely that more than one Set-Cookie header can be included in a server response. So this implementation parses out each cookie and builds a cookie string in the correct format.
Since we are now correctly building the cookie string ourselves you can remove the CookieStore and just pull the "cookie" value out of SharedPreferences and use the string that is returned in your setHeader call:
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String stringCookie = sharedPreferences.getString("cookie", "");
...
httpPost.setHeader("Cookie", cookie);
Keep in mind that although this implementation will work for you it won't take into consideration if cookies change throughout your session. Since you are the author of the web application you should be aware of whether or not cookies change - maybe when you log in it's the only time you will be given cookies to set in the browser and this solution will work for you. But a more robust solution will be to save out all of the cookies individually (instead of using editor.putString you can use editor.putStringSet to save out all of the cookie headers) then when you want to build a cookie for the respond you can .add() each individual cookie to the cookie store and then use the cookie store the same way you were before. This way each cookie by name is stored individually so that if you ever get another Set-Cookie header again for a cookie that you already have loaded in your client it will correctly overwrite that value with the updated cookie value.
private static CookieStore cookieStore = new BasicCookieStore();
private HttpClient client = new DefaultHttpClient();
private static HttpContext httpContext = new BasicHttpContext();
public static void main(String[] args) throws Exception {
String url = "http://www.codechef.com";
String account = "http://www.codechef.com/node?destination=node";
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
List<NameValuePair> postParams = http.getFormParams();
sendPost(url, postParams);
}
private void sendPost(String url, List<NameValuePair> postParams)
throws Exception {
HttpPost post = new HttpPost(url);
post.setHeader("Accept","text/plain");
post.setHeader("Accept-Language", "en-US");
post.setHeader("Connection", "keep-alive");
post.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = client.execute(post,httpContext);
List<Cookie> cook=cookieStore.getCookies();
if(cook==null)
System.out.println("Null");
else{
System.out.println(cook.size());
for(Cookie c:cook){
String cookieReader=c.getName()+" = "+c.getValue()+";domain= "+c.getDomain();
System.out.println(cookieReader);
}
}
}
public List<NameValuePair> getFormParams() throws UnsupportedEncodingException {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("name","name"));
paramList.add(new BasicNameValuePair("pass","pass"));
return paramList;
}
After the post method, the size of the cookie is 0, but I checked from the browser, and it shows sessionID cookie. But I cannot extract it using this code to authenticate user. Thank you.
You should pay attention on the HTML form fields.
There is often hidden fields required in order to achieve the post process correctly.
Take at look the html source of the login form on this website (inspect element...)
The form fields are: "user", "pass" plus two hidden fields "form_build_id" and "form_id".
Try adding this in your 'getFormParams' function:
paramList.add(new BasicNameValuePair("form_id","user_login_block"));
I'm POSTing some data to a server that is answering a 302 Moved Temporarily.
I want HttpClient to follow the redirect and automatically GET the new location, as I believe it's the default behaviour of HttpClient. However, I'm getting an exception and not following the redirect :(
Here's the relevant piece of code, any ideas will be appreciated:
HttpParams httpParams = new BasicHttpParams();
HttpClientParams.setRedirecting(httpParams, true);
SchemeRegistry schemeRegistry = registerFactories();
ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(clientConnectionManager, httpParams)
HttpPost postRequest = new HttpPost(url);
postRequest.setHeader(HTTP.CONTENT_TYPE, contentType);
postRequest.setHeader(ACCEPT, contentType);
if (requestBodyString != null) {
postRequest.setEntity(new StringEntity(requestBodyString));
}
return httpClient.execute(postRequest, responseHandler);
For HttpClient 4.3:
HttpClient instance = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
For HttpClient 4.2:
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());
For HttpClient < 4.2:
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy() {
/** Redirectable methods. */
private String[] REDIRECT_METHODS = new String[] {
HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME
};
#Override
protected boolean isRedirectable(String method) {
for (String m : REDIRECT_METHODS) {
if (m.equalsIgnoreCase(method)) {
return true;
}
}
return false;
}
});
The default behaviour of HttpClient is compliant with the requirements of the HTTP specification (RFC 2616)
10.3.3 302 Found
...
If the 302 status code is received in response to a request other
than GET or HEAD, the user agent MUST NOT automatically redirect the
request unless it can be confirmed by the user, since this might
change the conditions under which the request was issued.
You can override the default behaviour of HttpClient by sub-classing DefaultRedirectStrategy and overriding its #isRedirected() method.
It seem http redirect is disable by default. I try to enable, it work but I'm still got error with my problem. But we still can handle redirection pragmatically. I think your problem can solve:
So old code:
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("User-Agent");
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
long contentSize = httpResponse.getEntity().getContentLength();
This code will return contentSize = -1 if http redirect happend
And then I handle redirect by myself after trying enable default follow redirection
AndroidHttpClient client;
HttpGet httpGet;
HttpResponse response;
HttpHeader httpHeader;
private void handleHTTPRedirect(String url) throws IOException {
if (client != null)
client.close();
client = AndroidHttpClient.newInstance("User-Agent");
httpGet = new HttpGet(Network.encodeUrl(url));
response = client.execute(httpGet);
httpHeader = response.getHeaders("Location");
while (httpHeader.length > 0) {
client.close();
client = AndroidHttpClient.newInstance("User-Agent");
httpGet = new HttpGet(Network.encodeUrl(httpHeader[0].getValue()));
response = client.execute(httpGet);
httpHeader = response.getHeaders("Location");
}
}
In use
handleHTTPRedirect(url);
long contentSize = httpResponse.getEntity().getContentLength();
Thanks
Nguyen
My solution is using HttClient. I had to send the response back to the caller. This is my solution
CloseableHttpClient httpClient = HttpClients.custom()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
//this reads the input stream from POST
ServletInputStream str = request.getInputStream();
HttpPost httpPost = new HttpPost(path);
HttpEntity postParams = new InputStreamEntity(str);
httpPost.setEntity(postParams);
HttpResponse httpResponse = null ;
int responseCode = -1 ;
StringBuffer response = new StringBuffer();
try {
httpResponse = httpClient.execute(httpPost);
responseCode = httpResponse.getStatusLine().getStatusCode();
logger.info("POST Response Status:: {} for file {} ", responseCode, request.getQueryString());
//return httpResponse ;
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
logger.info(" Final Complete Response {} " + response.toString());
httpClient.close();
} catch (Exception e) {
logger.error("Exception ", e);
} finally {
IOUtils.closeQuietly(httpClient);
}
// Return the response back to caller
return new ResponseEntity<String>(response.toString(), HttpStatus.ACCEPTED);
For HttpClient v5, just use the below:
httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new DefaultRedirectStrategy() {
#Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
throws ProtocolException {
return false;
}
}).build();