Need help on RestTemplate exchange method - android

I need to do authentification from my app android by using spring boot i try to send the username and password like this:
HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
and make network request using restTemplate.exchange :
ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.POST,new HttpEntity<Object>(requestHeaders), Message.class);
but i still get null response.
this my code server :
Controller:
#Controller
public class RController {
#RequestMapping(value={"/welcome"})
public #ResponseBody Message getMessage() {
return new Message(100, "Congratulations!", "You have accessed a Basic
Auth protected resource.");
}
#RequestMapping(value={"/login"})
public String login() {
return "login";
}
}
config
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from user_roles where username=?");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
}
}

I believe RController class would need to be annotated with #RestController instead of #Controller

Related

Retrofit async calls with OAuth2

There are two ways to make a Retrofit call synchronous (with methods, returning values) and asynchronous (with callbacks).
Second one, async, works great out-of-the-box. But there is an issue, when it comes to OAuth2 authenticated access.
Can you recommend me a good RestAdapter, compatible with asynchronous retrofit calls.
I tried to use interceptors as follows, but it makes network calls on the main thread, which is not sufficient to me (Android). I am trying to use the following code (not mine).
public class SecuredRestBuilder extends RestAdapter.Builder {
private class OAuthHandler implements RequestInterceptor {
private boolean loggedIn;
private Client client;
private String tokenIssuingEndpoint;
private String username;
private String password;
private String clientId;
private String clientSecret;
private String accessToken;
public OAuthHandler(Client client, String tokenIssuingEndpoint, String username,
String password, String clientId, String clientSecret) {
super();
this.client = client;
this.tokenIssuingEndpoint = tokenIssuingEndpoint;
this.username = username;
this.password = password;
this.clientId = clientId;
this.clientSecret = clientSecret;
}
/**
* Every time a method on the client interface is invoked, this method is
* going to get called. The method checks if the client has previously obtained
* an OAuth 2.0 bearer token. If not, the method obtains the bearer token by
* sending a password grant request to the server.
*
* Once this method has obtained a bearer token, all future invocations will
* automatically insert the bearer token as the "Authorization" header in
* outgoing HTTP requests.
*
*/
#Override
public void intercept(RequestFacade request) {
// If we're not logged in, login and store the authentication token.
if (!loggedIn) {
try {
// This code below programmatically builds an OAuth 2.0 password
// grant request and sends it to the server.
// Encode the username and password into the body of the request.
FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput();
to.addField("username", username);
to.addField("password", password);
// Add the client ID and client secret to the body of the request.
to.addField("client_id", clientId);
to.addField("client_secret", clientSecret);
// Indicate that we're using the OAuth Password Grant Flow
// by adding grant_type=password to the body
to.addField("grant_type", "password");
// The password grant requires BASIC authentication of the client.
// In order to do BASIC authentication, we need to concatenate the
// client_id and client_secret values together with a colon and then
// Base64 encode them. The final value is added to the request as
// the "Authorization" header and the value is set to "Basic "
// concatenated with the Base64 client_id:client_secret value described
// above.
String base64Auth = BaseEncoding.base64().encode(new String(clientId + ":" + clientSecret).getBytes());
// Add the basic authorization header
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Authorization", "Basic " + base64Auth));
// Create the actual password grant request using the data above
Request req = new Request("POST", tokenIssuingEndpoint, headers, to);
// Request the password grant.
Response resp = client.execute(req);
// Make sure the server responded with 200 OK
if (resp.getStatus() < 200 || resp.getStatus() > 299) {
// If not, we probably have bad credentials
throw new SecuredRestException("Login failure: "
+ resp.getStatus() + " - " + resp.getReason());
} else {
// Extract the string body from the response
String body = IOUtils.toString(resp.getBody().in());
// Extract the access_token (bearer token) from the response so that we
// can add it to future requests.
accessToken = new Gson().fromJson(body, JsonObject.class).get("access_token").getAsString();
// Add the access_token to this request as the "Authorization"
// header.
request.addHeader("Authorization", "Bearer " + accessToken);
// Let future calls know we've already fetched the access token
loggedIn = true;
}
} catch (Exception e) {
throw new SecuredRestException(e);
}
}
else {
// Add the access_token that we previously obtained to this request as
// the "Authorization" header.
request.addHeader("Authorization", "Bearer " + accessToken );
}
}
private String username;
private String password;
private String loginUrl;
private String clientId;
private String clientSecret = "";
private Client client;
#Override
public RestAdapter build() {
if (username == null || password == null) {
throw new SecuredRestException(
"You must specify both a username and password for a "
+ "SecuredRestBuilder before calling the build() method.");
}
if (client == null) {
client = new OkClient();
}
OAuthHandler hdlr = new OAuthHandler(client, loginUrl, username, password, clientId, clientSecret);
setRequestInterceptor(hdlr);
return super.build();
}
// setters and getters here
}
So, I ended up splitting RestAdapter class into two separate classes. The first one gets token. Another one is a RestAdapter class that takes the token as input.
Class for getting token:
public class GetTokenRequest {
public static final String TAG = GetTokenRequest.class.getCanonicalName();
public static final String CLIENT_ID = AccessPoint.CLIENT_ID;
public static final String CLIENT_SECRET = AccessPoint.CLIENT_SECRET;
public static final String ENDPOINT = AccessPoint.ENDPOINT;
public static final String TOKEN_PATH = AccessPoint.TOKEN_PATH;
public interface Listener {
void onGetTokenSucess(String token);
void onGetTokenUnauthorized();
void onGetTokenFailure();
}
public static void getAccessToken(Client client, String username, String password,
final Listener callback) {
try {
// This code below programmatically builds an OAuth 2.0 password
// grant request and sends it to the server.
// Encode the username and password into the body of the request.
FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput();
to.addField("username", username);
to.addField("password", password);
// Add the client ID and client secret to the body of the request.
to.addField("client_id", CLIENT_ID);
to.addField("client_secret", CLIENT_SECRET);
// Indicate that we're using the OAuth Password Grant Flow
// by adding grant_type=password to the body
to.addField("grant_type", "password");
// The password grant requires BASIC authentication of the client.
// In order to do BASIC authentication, we need to concatenate the
// client_id and client_secret values together with a colon and then
// Base64 encode them. The final value is added to the request as
// the "Authorization" header and the value is set to "Basic "
// concatenated with the Base64 client_id:client_secret value described
// above.
String base64Auth = BaseEncoding.base64()
.encode(new String(CLIENT_ID + ":" + CLIENT_SECRET).getBytes());
// Add the basic authorization header
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Authorization", "Basic " + base64Auth));
// Create the actual password grant request using the data above
Request req = new Request("POST", ENDPOINT + TOKEN_PATH, headers, to);
// Request the password grant.
Response resp = client.execute(req);
if (resp == null) {
Log.e(TAG, "resp is null");
callback.onGetTokenFailure();
return;
}
int status = resp.getStatus();
// Make sure the server responded with 200 OK
if (status >= 200 && status < 300) {
Log.e(TAG, "getToken response code is okay");
// Extract the string body from the response
final String body = IOUtils.toString(resp.getBody().in());
// Extract the access_token (bearer token) from the response so that we
// can add it to future requests.
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
callback.onGetTokenSucess(new Gson().fromJson(body, JsonObject.class)
.get("access_token").getAsString());
}
});
} else if (status == HttpStatus.SC_UNAUTHORIZED
|| status == HttpStatus.SC_BAD_REQUEST) {
Log.e(TAG, "getToken response code is 401");
// Incorrect credentials
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
callback.onGetTokenUnauthorized();
}
});
} else {
// Other error
Log.e(TAG, "getToken response code - other");
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
((LoginActivity) callback).onGetTokenFailure();
}
});
}
} catch (Exception e) {
Log.e(TAG, "Exception caught");
Log.e(TAG, e.toString());
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
callback.onGetTokenFailure();
}
});
}
}
}
RestAdapter class:
public class SecuredRestAdapter extends RestAdapter.Builder {
private class OAuthHandler implements RequestInterceptor {
private boolean loggedIn;
private Client client;
private String tokenIssuingEndpoint;
private String username;
private String password;
private String clientId;
private String clientSecret;
private String accessToken;
public OAuthHandler(Client client, String accessToken) {
super();
this.client = client;
this.accessToken = accessToken;
}
#Override
public void intercept(RequestFacade request) {
// Add the access_token that we previously obtained to this request as
// the "Authorization" header.
request.addHeader("Authorization", "Bearer " + accessToken);
}
}
private String loginUrl;
private Client client;
private String token;
public SecuredRestAdapter setLoginEndpoint(String endpoint){
loginUrl = endpoint;
return this;
}
#Override
public SecuredRestAdapter setEndpoint(String endpoint) {
return (SecuredRestAdapter) super.setEndpoint(endpoint);
}
#Override
public SecuredRestAdapter setEndpoint(Endpoint endpoint) {
return (SecuredRestAdapter) super.setEndpoint(endpoint);
}
#Override
public SecuredRestAdapter setClient(Client client) {
this.client = client;
return (SecuredRestAdapter) super.setClient(client);
}
#Override
public SecuredRestAdapter setClient(Provider clientProvider) {
client = clientProvider.get();
return (SecuredRestAdapter) super.setClient(clientProvider);
}
#Override
public SecuredRestAdapter setErrorHandler(ErrorHandler errorHandler) {
return (SecuredRestAdapter) super.setErrorHandler(errorHandler);
}
#Override
public SecuredRestAdapter setExecutors(Executor httpExecutor,
Executor callbackExecutor) {
return (SecuredRestAdapter) super.setExecutors(httpExecutor,
callbackExecutor);
}
#Override
public SecuredRestAdapter setRequestInterceptor(
RequestInterceptor requestInterceptor) {
return (SecuredRestAdapter) super
.setRequestInterceptor(requestInterceptor);
}
#Override
public SecuredRestAdapter setConverter(Converter converter) {
return (SecuredRestAdapter) super.setConverter(converter);
}
#Override
public SecuredRestAdapter setProfiler(#SuppressWarnings("rawtypes") Profiler profiler) {
return (SecuredRestAdapter) super.setProfiler(profiler);
}
#Override
public SecuredRestAdapter setLog(Log log) {
return (SecuredRestAdapter) super.setLog(log);
}
#Override
public SecuredRestAdapter setLogLevel(LogLevel logLevel) {
return (SecuredRestAdapter) super.setLogLevel(logLevel);
}
public SecuredRestAdapter setToken(String token) {
this.token = token;
return this;
}
#Override
public RestAdapter build() {
if (this.token == null || this.token.equals(""))
throw new SecuredRestAdapterException(
"Token must be provided, when calling SecuredRestAdapter");
if (client == null) {
client = new OkClient();
}
OAuthHandler hdlr = new OAuthHandler(client, token);
setRequestInterceptor(hdlr);
return super.build();
}
}
Exception class:
public class SecuredRestAdapterException extends RuntimeException {
public SecuredRestAdapterException(String message) {
super(message);
}
}

How to return different code and error with MockRestAdapter

I use MockRestAdapter to return mock data in my tests, but I'd also like to test errors (401, 503, UnknownHostException, etc)
For SocketTimeoutException, there's an API, but how about different response code?
I've tried MockWebServer but no matter what I enqueue, I always get a 200 with the mock data from the adapter.
update: I want to run my tests like this:
#RunWith(AndroidJUnit4.class)
#LargeTest
public class LoginActivityTest {
#Test public void goodCredentials() {
activity.login("username", "password");
assert(...); // Got back 200 and user object (from mock)
}
#Test public void wrongCredentials() {
activity.login("username", "wrong_password");
something.setResponse(401, "{error: wrong password}");
assert(...);
}
#Test public void someError() {
activity.login("username", "password");
something.setResponse(503, "{error: server error}");
assert(...);
}
}
update 2:
Found something, rather ugly, but does what I need:
MockApi implements ServiceApi {
public static Throwable throwable;
#Override login(Callback<User> callback) {
if (throwable != null) {
sendError(callback)
} else {
callback.success(new User("{name:test}"));
}
}
private void sendError(Callback callback) {
callback.failure(RetrofitError.unexpectedError("", throwable));
}
}
public class LoginActivityTest {
#Test public void someError() {
MockApi.throwable = new InterruptedIOException()
activity.login("username", "password");
// Assert having a time out message
}
#Test public void someError() {
MockApi.throwable = new UnknownHostException()
activity.login("username", "password");
// Assert having a no internet message
}
}
Still working on it, so any feedback will help :)
It's fairly easy to do. You just need to implement Client and pass it when you build your mock RestAdapter.
Creating client with appropriate response:
Client client = new Client() {
#Override public Response execute(Request request) throws IOException {
final String reason = "Some reason.";
final List<Header> headers = new ArrayList<>();
final TypedString body = new TypedString("");//could be json or what ever you want
final int status = 401;
return new Response(request.getUrl(), status, reason, headers, body);
}
};
And passing it to your RestAdapter.Builder:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.com")
.setClient(client)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
restAdapter.create(API.class);

RETROFIT & AUTH COOKIE

I need to know how to add an authorization cookie header in retrofit. I have seen advice like using request intercepter etc. Below is what I am trying, but is this correct? First of all I already needed a RequestAdatper to get the session id the first time around. This can only be set by the builder of the request adapter. But I needed to make a request just to get the session id in the first place. Do I need two rest adapters one to get the sessionId and another one after I have obtained it. What I really need is a method on adapter to set the cookie after I get it but it does not appear to be such a method. This is getting awkward. How do I set authorization cookie in retrofit? I don't see this in FAQ or tutorials.
RequestInterceptor requestInterceptor = new RequestInterceptor()
{
#Override
public void intercept(RequestFacade request) {
request.addHeader("Set-Cookie", "sessionId="+sessionIdentifier);
}
};
RestAdapter.Builder().setServer(serverURL)..setRequestIntercepter(requestIntercepter).build();
// but I don't have sessionId when this is first issued ???
Keep a reference to the interceptor and treat it as a singleton like you would be RestAdapter itself.
public class ApiHeaders implements RequestInterceptor {
private String sessionId;
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public void clearSessionId() {
sessionId = null;
}
#Override public void intercept(RequestFacade request) {
if (sessionId != null) {
request.setHeader(...);
}
}
}
Now, simply call setSessionId after your authentication call. All subsequent requests will include the header.
You can get the cookies like this
public class MyCookieManager extends CookieManager {
#Override
public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {
super.put(uri, stringListMap);
if (stringListMap != null && stringListMap.get("Set-Cookie") != null)
for (String string : stringListMap.get("Set-Cookie")) {
if (string.contains("JSESSIONID")) {
Preference.getInstance().setSessionId(string);
}
}
}
}
Use this to set the CookieHandler
MyCookieManager myCookieManager = new MyCookieManager();
CookieHandler.setDefault(myCookieManager);
and then use it like this in your request Interceptor
String sessionId = preference.getSessionId();
if (sessionId != null)
requestFacade.addHeader(Cookie, sessionId);
Step 1. Parse Response headers.
Call this method inside your Callback in overriden success method.
/**
* Method extracts cookie string from headers
* #param response with headers
* #return cookie string if present or null
*/
private String getCookieString(Response response) {
for (Header header : response.getHeaders()) {
if (null!= header.getName() && header.getName().equals("Set-Cookie")) {
return header.getValue();
}
}
return null;
}
Step 2. Write some static class or singleton to keep cookies and your RequestInterceptor instance. Inside RequestInterceptor override intercept method to add your cookies to Header.
public class RestAdapter {
private static String cookies;
public static String getCookies() {
return cookies;
}
public static void setCookies(String cookies) {
RestAdapter.cookies = cookies;
}
/**
* Injects cookies to every request
*/
private static final RequestInterceptor COOKIES_REQUEST_INTERCEPTOR = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
if (null != cookies && cookies.length() > 0) {
request.addHeader("Cookie", cookies);
}
}
};
public static final RestInterface getService() {
return new RestAdapter.Builder()
.setEndpoint(Config.ENDPOINT)
.setRequestInterceptor(COOKIES_REQUEST_INTERCEPTOR)
.setConverter(new JacksonConverter())
.setLogLevel(RestAdapter.LogLevel.NONE)
.build()
.create(RestInterface.class);
}
}
According to #sbtgE's answer, but with some corrections. CookieHandler.getDefault() may be null, so I use CookieManager.
app's build.gradle:
dependencies {
...
compile 'com.squareup.okhttp3:okhttp-urlconnection:3.4.1'
}
Setting up Retrofit:
service = new Retrofit.Builder()
.baseUrl(/* your base URL */)
.addConverterFactory(/* your favourite converter */)
.client(
new OkHttpClient.Builder()
// this line is the important one:
.cookieJar(new JavaNetCookieJar(new CookieManager()))
.build())
.build()
.create(YourInterface.class);
Simple solution using lib. compile com.squareup.okhttp3:okhttp-urlconnection:3.2.0.
JavaNetCookieJar jncj = new JavaNetCookieJar(CookieHandler.getDefault());
OkHttpClient.Builder().cookieJar(jncj).build();

Trying to get an Android annotations spring RESTful client api working, couple of problems

I can't seem to figure out how to get android annotations rest client to work I'm having 2 main issues.
A)How to parse the generic json response and get the meaningful key
B)How to add parameters
For the first problem all responses come back as a json string fomatted like this
{"success":,"message":"","data":{}}
Where success is boolean message is a string and data is going to be the main data I want to parse that may be a boolean, an array, a string or an int
I'm pretty sure I need to intercept the response and handle the code but I'm not sure how to do that
Lets use a real response that look something like this
{"success":true,"message":"random message","data":{"profile":{"id":"44","user_id":"44","name":"Matt","username":"mitch","icon":"b1da7ae15027b7d6421c158d644f3220.png","med":"2a3df53fb39d1d8b5edbd0b93688fe4a.png","map":"b7bfed1f456ca4bc8ca748ba34ceeb47.png","background":null,"mobile_background":null}}
First in my interceptor I want to see if the boolean key "success" is true and then return the data value
#EBean
public class RestInterceptor implements ClientHttpRequestInterceptor {
final String TAG = "rest";
#Bean
AuthStore authStore;
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] data, ClientHttpRequestExecution execution)
throws IOException{
//Need to set the api key here but nothing happens code quits
// Log.d("Rest",authStore.getApiKey());
HttpHeaders headers = request.getHeaders();
headers.set("api_key","");
ClientHttpResponse resp = execution.execute(request, data);
HttpStatus code = resp.getStatusCode();
if(code.value() == 200){
Log.d(TAG,"success code 200");
//valid http request but is it a valid API request?
//perform some logic of if success == true in root json object
//if true cast return data key
}
else{
Log.d(TAG,"fail code" + code.toString());
}
return resp;
}
}
The second problem is sending params with the http request that have an api key and a session key, I define the application class like this
#EApplication
public class MyApp extends Application {
final String TAG = "app";
#Bean
AuthStore authStore;
#RestService
RestClient restClient;
public void onCreate() {
super.onCreate();
init();
}
#AfterInject
public void init() {
authStore.setApiKey("dummy_key");
Log.d(TAG, "api key set to " + authStore.getApiKey());
}
}
With the AuthStore class like this
#EBean(scope = Scope.Singleton)
public class AuthStore {
public String apiKey,sessionKey;
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}
}
Basically I'm setting a dummy api key at the application level in a singleton, which I should be able to access in the rest interceptor interface but the code just quits without errors I'm basically following this guide https://github.com/excilys/androidannotations/wiki/Authenticated-Rest-Client
Finally I have an activity class which injects the app dependency which has refrence to the rest http class and the authstore class
#EActivity(R.layout.activity_login)
public class LoginActivity extends Activity {
#App
MyApp app;
#ViewById
TextView email;
#ViewById
TextView password;
#ViewById
Button loginButton;
#AfterInject
public void init() {
Log.d(app.TAG, "api in login key set to " + app.authStore.getApiKey());
}
#Click
#Trace
void loginButton() {
login(email.toString(), password.toString());
}
#Background
void login(String email, String password) {
app.restClient.forceLogin();
}
}
Sorry if it's a lot of info, I've been searching for a while and can't figure this out!
thanks in advance
I'm not known with the library you're using (annotations, spring) but it seems to me that you are struggling with parsing the success = true because that is not supposed to be in the JSON.
The JSON should preferably represent a class in your app 1on1 so you can easily map that into an object.
Communication between your app and the webservice, regarding the status of requests should go into the headers.
Like this you can check a request's headers, before parsing the JSON.
This is mathod I am using to parse any JSON object recursively.
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}

Maintaining user session in Android

I am trying to make social network application for Android. My question is how to maintain user session when user logs in?
Please help me to find the solution for the above question.
try
public class Session {
private static String sessionId;
private static String userRole;
public static void setSessionId(String sessionId) {
Session.sessionId = sessionId;
}
public static String getSessionId() {
return sessionId;
}
}
Use this class and import it in every other activity. You can define your own functions to maintain your specific session data
http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
Please look at the above link. It is detailed pretty well.
Use a singleton to maintain the user session.
I use DefaultHttpClient with HttpRequestInterceptor and HttpResponseInterceptor.
Something similar to this:
public class HTTPClients {
private static DefaultHttpClient _defaultClient;
private static String session_id;
private static HTTPClients _me;
private HTTPClients() {
}
public static DefaultHttpClient getDefaultHttpClient(){
if ( _defaultClient == null ) {
_defaultClient = new DefaultHttpClient();
_me = new HTTPClients();
_defaultClient.addResponseInterceptor(_me.new SessionKeeper());
_defaultClient.addRequestInterceptor(_me.new SessionAdder());
}
return _defaultClient;
}
private class SessionAdder implements HttpRequestInterceptor {
#Override
public void process(HttpRequest request, HttpContext context)
throws HttpException, IOException {
Log.d("SessionKeeper", "Adding session with the following string: " + session_id);
if ( session_id != null ) {
request.setHeader("Cookie", session_id);
}
}
}
private class SessionKeeper implements HttpResponseInterceptor {
#Override
public void process(HttpResponse response, HttpContext context)
throws HttpException, IOException {
Header[] headers = response.getHeaders("Set-Cookie");
if ( headers != null && headers.length == 1 ){
Log.d("SessionKeeper", "Keeping session with the following string: " + headers[0].getValue());
session_id = headers[0].getValue();
}
}
}
}
I have the similar problem on my android client side when I am trying to send that session id ,the server side is creating a new session...but what you check at android client side that you are not creating the DefaulthttpClient twice... create the httpclient just once say main activity and pass the objects in other activity ...... dont create second HttpClient
Create session using SharedPreferences.
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
now after making this class when u want to use this use like this make object og this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
//and now we set sharedpreference then use this like
session.setusename("USERNAME");
now when ever u want to get username then same work for session object and call this
session.getusename();
best of luck :) same for password

Categories

Resources