我正在創建一個Native Android應用程序。我將使用Rest Api從我的Android設備登錄到Drupal。我設置的Drupal服務工作正常。我用郵差測試了它。使用Rest API登錄Android中的Drupal
我是一名初學者,遇到一些問題,找到解釋如何做到這一點的好資源和新資源。我發現這個老教程。不幸的是,我無法讓它工作。
如果您知道更好的書寫方式,請告訴我。 任何幫助,將不勝感激。
public class LoginActivity extends AppCompatActivity {
public String session_name;
public String session_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
//background task to login into Drupal
private class LoginProcess extends AsyncTask<String, Integer, Integer> {
protected Integer doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
//set the remote endpoint URL
HttpPost httppost = new HttpPost("http://localhost:8012/Adrupal/apistuff/user/login.json");
try {
//get the UI elements for username and password
EditText username= (EditText) findViewById(R.id.editUsername);
EditText password= (EditText) findViewById(R.id.editPassword);
JSONObject json = new JSONObject();
//extract the username and password from UI elements and create a JSON object
json.put("name", username.getText().toString().trim());
json.put("pass", password.getText().toString().trim());
//add serialised JSON object into POST request
StringEntity se = new StringEntity(json.toString());
//set request content type
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
//send the POST request
HttpResponse response = httpclient.execute(httppost);
//read the response from Services endpoint
String jsonResponse = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(jsonResponse);
//read the session information
session_name=jsonObject.getString("session_name");
session_id=jsonObject.getString("sessid");
Toast.makeText(LoginActivity.this, session_id + "this" + session_name, Toast.LENGTH_LONG).show();
return 0;
}catch (Exception e) {
Log.v("Error adding article", e.getMessage());
}
return 0;
}
protected void onPostExecute(Integer result) {
//create an intent to start the ListActivity
Intent intent = new Intent(LoginActivity.this, ListActivity.class);
//pass the session_id and session_name to ListActivity
intent.putExtra("SESSION_ID", session_id);
intent.putExtra("SESSION_NAME", session_name);
//start the ListActivity
Toast.makeText(LoginActivity.this, session_id + "this" + session_name, Toast.LENGTH_LONG).show();
startActivity(intent);
}
}
//click listener for doLogin button
public void doLoginButton_click(View view){
new LoginProcess().execute();
}
}
這會返回什麼錯誤? – technico
我犯了一個愚蠢的錯誤。 Drupal站點在我的機器上運行在本地主機上。當我將它移動到網上時,它工作。不管怎麼說,還是要謝謝你。 – Kong