Android将JSON发布到Web服务php并从服务接收JSON

时间:2013-01-24 00:44:13

标签: php android json post

我试图在Android中编写一个登录服务,通过在Web服务JSON中处理完JSON后返回给我在PHP中的Web服务。我的问题是发送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);
        }

    }

}

2 个答案:

答案 0 :(得分: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中的服务器获取结果,您需要将返回的字符串从服务器转换为JsonObject,并在AsyncTask的onPostExecute方法中将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

}

答案 1 :(得分:0)

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