我正在创建一个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 {
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();
}
}
2016-08-06
Kong
+0
这会返回什么错误? –
+0
我犯了一个愚蠢的错误。 Drupal站点在我的机器上运行在本地主机上。当我将它移动到网上时,它工作。不管怎么说,还是要谢谢你。 –