1

我试图通过将 JSON 发送到我在 PHP 中拥有的 web 服务来在 android 中编写登录服务,因为它在 web 服务中处理后返回 JSON。我的问题是发送 JSON,然后在 android 应用程序中读取 JSON。我已经使用 ASyncTask 在应用程序中找到了基本的发布,但我不确定从那里去哪里,我一直在做很多搜索,我现在有点难过。非常感谢任何帮助!

这是我的 .java 文件

package com.example.logintest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

private static final String APP_TAG = "demo";
public static EditText txtUserName;
public static EditText txtPassword;
Button btnLogin;
Button btnCancel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtUserName=(EditText)this.findViewById(R.id.txtUname);
        txtPassword=(EditText)this.findViewById(R.id.txtPwd);
        btnLogin=(Button)this.findViewById(R.id.btnLogin);
        btnLogin=(Button)this.findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new OnClickListener() {


    public void onClick(View v) {
        // TODO Auto-generated method stub
        new loginTask().execute();
        /*if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
            Toast.makeText(MainActivity.this, "Login Successful",Toast.LENGTH_LONG).show();
        } else{
        Toast.makeText(MainActivity.this, "Invalid Login",Toast.LENGTH_LONG).show();
        }*/

    }
   });   
   }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    public static String postHttpResponse(URI absolute) {
        Log.d(APP_TAG, "Going to make a post request");
        StringBuilder response = new StringBuilder();
        String username = txtUserName.getText().toString();
        String password = txtPassword.getText().toString();
        try {
            HttpPost post = new HttpPost();
            post.setURI(absolute);
            List params = new ArrayList();
            params.add(new BasicNameValuePair("tag", "login"));
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));
            post.setEntity(new UrlEncodedFormEntity(params));
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                Log.d(APP_TAG, "HTTP POST succeeded");
                HttpEntity messageEntity = httpResponse.getEntity();
                InputStream is = messageEntity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
            } else {
                Log.e(APP_TAG, "HTTP POST status code is not 200");
            }
        } catch (Exception e) {
            Log.e(APP_TAG, e.getMessage());
        }
        Log.d(APP_TAG, "Done with HTTP posting");
        return response.toString();
    }

    class loginTask extends AsyncTask<Object, Object, String> { 

        //check if server is online
        protected String doInBackground(Object... arg0) {
            URI absolute = null;
            try {
                absolute = new URI("http://10.0.2.2/service/");
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return postHttpResponse(absolute);
        }

        //set status bar to offline if flag is false
        protected void onPostExecute(String xml) {
            //XMLfromString(xml);
        }

    }

}
4

2 回答 2

3

您可以将用户名和密码作为 jsonobject 发送到服务器:

//your code here....
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", password);

HttpPost post = new HttpPost();
post.setURI(absolute);
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", "login"));
params.add(new BasicNameValuePair("loginjson",json.toString()));
post.setEntity(new UrlEncodedFormEntity(params));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(post);
//your code here....

在服务器端从 loginjson queryString 检索 json 对象。

为了从 json 中的服务器返回结果,您需要将返回的字符串从服务器转换为 AsyncTask 的 onPostExecute 方法中的 JsonObject ir JsonArray,如下所示:

protected void onPostExecute(String jsonstring) {
     // if server returning jsonobject 
       JSONObject jsonobj=new JSONObject(jsonstring);
          // get values from jsonobject

      // if server returning jsonArray
       JSONArray jsonarray=new JSONArray(jsonstring);
          // get values from JSONArray

}
于 2013-01-24T02:03:16.863 回答
0

在我们的应用程序中,我们使用 php 将 json 发送到我们的服务。我不直接以 json 格式发送它,而是以字符串数组格式发送它,并让 php 对 json 进行编码,以便在我从服务器获得响应时接收回数据,我只是将它放在字符串中,然后在 java 中使用 JSONObject我将其转换为 json 并解析数据。

于 2013-01-24T01:30:33.853 回答