Lasciami descrivere la mia domanda, Sto recuperando i dati dal sito web URL JSON (sito Web Drupal), i dati sono in formato JSON. Nella mia applicazione la funzionalità di login funziona perfettamente. L'utente & è convalidato sul server. Sto anche recuperando altri dati (URL JSON) dal server & visualizzati nella mia applicazione Android. Ora, il problema è che non riesco ad accedere ai dati JSON delle pagine, dove è richiesto l'accesso, perché il mio accesso non viene mantenuto in tutta l'applicazione Android.Come mantenere l'accesso al server in tutta l'applicazione nativa Android?
Ho cercato su StackOverflow & google ho ottenuto questi collegamenti & provato ma non so come usarli nel mio codice: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html
Qui è il JSON vuoto che viene dal sito drupal senza login.
{
"nodes": []
}
Ecco il JSON da Drupal sito-dopo il login (http://www.mywebsite.com/user/login) & ricaricare la pagina http://www.mywebsite.com/myaccount-page sul sito - in computer di browser web. significa che il browser web del computer mantiene automaticamente la sessione di accesso.
{
"nodes": [
{
"node": {
"Uid": "51",
"Username": "anand",
"Name": "anand",
"Address": "\n\tAt- vadodara Nr. Kareli Baugh",
"Date of Birth": "1998-08-20",
"Occupation": "student",
"Member Since": "36 weeks 6 days"
}
}
]
}
Ma in applicazione Android che non lo fa automaticamente. Quindi voglio mantenere questa sessione in Android in modo che possa accedere in un'applicazione Android, dopo il reindirizzamento di accesso a un'altra attività di pagina & ottenere i dati JSON lì. Ecco il mio codice:
LoginActivity.java
public void onClick(View v) {
String uName = editUser.getText().toString();
String Password = editPass.getText().toString();
if(uName.equals("") | Password.equals(""))
{
Toast.makeText(getApplicationContext(), "Enter the Username and Password",Toast.LENGTH_SHORT).show();
}
else{
String strResponse = util.makeWebCall(loginURL,uName,Password);
System.out.println("=========> Response from login page=> " + strResponse);
try{
if (strResponse.substring(KEY_SUCCESS) != null) {
txterror.setText("");
Intent inlogin = new Intent(LoginActivity.this,
post_myprofile.class);
inlogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inlogin);
//finish();
}
else
{
txterror.setText("Username and Password Not valid !!!");
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
});
btngotoregister.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1 = new Intent(getApplicationContext(),
RegisterActivity.class);
// intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent1);
}
});
}
}
metodo makeWebCall in util.java
util.java
public static String makeWebCall(String url, String uname,String pass)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",uname));
params.add(new BasicNameValuePair("password",pass));
UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(params);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
post.setEntity(formEntity);
try {
//post.setEntity(new StringEntity(requestString));
HttpResponse response = client.execute(post);
System.out.println("=========> Responsehello => "+response);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
return iStream_to_String(is);
}
else
{
return "Hello This is status ==> :"+String.valueOf(statusCode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Ora con questo codice il login ha avuto successo & Ho ricevuto la risposta JSON dal server con i dettagli. & reindirizza l'attività della pagina alla seconda pagina per il profilo utente. On 2a pagina Non riesco a ottenere i dati JSON del profilo utente. Come accennato in precedenza, ricevo il JSON vuoto perché la sessione non viene mantenuta.
Ecco il codice della seconda pagina di attività.
post_myprofile.java
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "http://www.cheerfoolz.com/myaccount-page";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse
.getJSONArray(API.cheerfoolz_myprofile.NODES);
metodo makewebcall per il profilo in util.java
util.java
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
/* Log.i(getClass().getSimpleName(),
"Error => " + statusCode + " => for URL " + url);*/
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
return iStream_to_String(is);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1)
{
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
io sono sempre JSON vuoto qui in questa pagina - che ho menzionato sopra. quindi come mantenere la sessione in questa attività profilo utente & ottenere i dati?
Grazie per l'ascolto.
La ringrazio molto .. Questo è stato di grande aiuto :) – Dave