【问题标题】:Android post JSON to web service php and recieving JSON from serviceAndroid 将 JSON 发布到 Web 服务 php 并从服务中接收 JSON
【发布时间】:2013-01-24 00:44:13
【问题描述】:

我试图通过将 JSON 发送到我在 PHP 中拥有的 web 服务,在 web 服务中处理 JSON 返回后,在 android 中编写登录服务。我的问题是发送 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);
        }

    }

}

【问题讨论】:

  • 您有可用的 Json 格式的实际响应吗?
  • 发送到服务器的 JSON 将通过数据库进行处理,并且根据发送的信息,如果成功与否,如果不成功,则返回是什么错误。还是您的意思是您想要从服务器发送的响应?
  • 要获得出色的 Java JSON 库,请查看 GSON。体积小、速度快、使用方便:code.google.com/p/google-gson
  • @Adonai:你的代码看起来是 f9,那么你在哪里遇到问题?以及你是如何在服务器上从 android 设备接收 json 的?
  • @ρяσѕρєя K 我没有发送任何 JSON 但我的问题是我不知道该怎么做

标签: php android json post


【解决方案1】:

您可以将用户名和密码作为 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

}

【讨论】:

  • 我正在看这个试图让它对我的网络服务做一些事情,这样你就知道我正在使用它而不是忽略它
  • 好的,我已经成功地以 JSON 格式响应,感谢您的帮助。我使用了我原来的发送代码,但使用了你的 onPostExecute 代码
  • @Adonai:如果这个答案帮助你解决当前问题,你能把它标记为答案吗?谢谢
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多