【问题标题】:Cant seem to send JSONObject from android to remote server似乎无法将 JSONObject 从 android 发送到远程服务器
【发布时间】:2013-09-06 15:33:40
【问题描述】:

我一直在寻找一种将数据发送到远程服务器上的 php 页面的方法,但似乎无法让它工作......我修改了 here 上类似问题的代码 但它仍然不起作用..我必须将 httppost 放在 asynctask 中吗?我该怎么做?代码:

public class gameOver extends Activity {
//TextView hiscores;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gameover);

    final Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Perform action on click

            Toast.makeText(gameOver.this, "button was pressed",
                    Toast.LENGTH_SHORT).show();
            try {
                JSONObject json = new JSONObject(); 
                json.put("timestamp", 1351181576.64078); 
                json.put("name", "engine_speed");
                json.put("value", 714.0);
                postData(json);

                JSONObject json2 = new JSONObject(); 
                json2.put("timestamp", 1351181576.7207818); 
                json2.put("name", "steering_wheel_angle");
                json2.put("value", 11.1633);
                postData(json2);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });     
}

public void postData(JSONObject json) throws JSONException {
    HttpClient httpclient = new DefaultHttpClient();
String URL = "http://www.mysite.com/s.php";
    try { 
        HttpPost httppost = new HttpPost(URL);

        List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);    
        nvp.add(new BasicNameValuePair("json", json.toString()));

        httppost.setEntity(new UrlEncodedFormEntity(nvp));
        HttpResponse response = httpclient.execute(httppost); 

        if(response != null) {
            InputStream is = response.getEntity().getContent();
            //input stream is response that can be shown back on android
            Toast.makeText(gameOver.this, (CharSequence) is,
                    Toast.LENGTH_SHORT).show();
        }else{       Toast.makeText(gameOver.this, "data Not sent",
                Toast.LENGTH_SHORT).show();}


    }catch (Exception e) {
        e.printStackTrace();
    } 
}

}

日志猫:

09-06 11:45:28.986: W/System.err(30433): android.os.NetworkOnMainThreadException
09-06 11:45:28.986: W/System.err(30433):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
09-06 11:45:28.986: W/System.err(30433):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-06 11:45:28.986: W/System.err(30433):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-06 11:45:28.986: W/System.err(30433):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-06 11:45:28.986: W/System.err(30433):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-06 11:45:28.986: W/System.err(30433):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-06 11:45:28.986: W/System.err(30433):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-06 11:45:28.986: W/System.err(30433):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-06 11:45:28.986: W/System.err(30433):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-06 11:45:28.986: W/System.err(30433):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-06 11:45:28.986: W/System.err(30433):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-06 11:45:28.986: W/System.err(30433):    at com.example.testgallery.gameOver.postData(gameOver.java:90)
09-06 11:45:28.986: W/System.err(30433):    at com.example.testgallery.gameOver$1.onClick(gameOver.java:65)
09-06 11:45:28.986: W/System.err(30433):    at android.view.View.performClick(View.java:4240)
09-06 11:45:28.986: W/System.err(30433):    at android.view.View$PerformClick.run(View.java:17721)
09-06 11:45:28.986: W/System.err(30433):    at android.os.Handler.handleCallback(Handler.java:730)
09-06 11:45:28.986: W/System.err(30433):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-06 11:45:28.986: W/System.err(30433):    at android.os.Looper.loop(Looper.java:137)
09-06 11:45:28.986: W/System.err(30433):    at android.app.ActivityThread.main(ActivityThread.java:5103)
09-06 11:45:28.986: W/System.err(30433):    at java.lang.reflect.Method.invokeNative(Native Method)
09-06 11:45:28.986: W/System.err(30433):    at java.lang.reflect.Method.invoke(Method.java:525)
09-06 11:45:28.986: W/System.err(30433):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-06 11:45:28.996: W/System.err(30433):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-06 11:45:28.996: W/System.err(30433):    at dalvik.system.NativeStart.main(Native Method)
09-06 11:45:28.996: W/System.err(30433): android.os.NetworkOnMainThreadException
09-06 11:45:28.996: W/System.err(30433):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
09-06 11:45:28.996: W/System.err(30433):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-06 11:45:28.996: W/System.err(30433):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-06 11:45:28.996: W/System.err(30433):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-06 11:45:28.996: W/System.err(30433):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-06 11:45:28.996: W/System.err(30433):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-06 11:45:28.996: W/System.err(30433):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-06 11:45:28.996: W/System.err(30433):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-06 11:45:28.996: W/System.err(30433):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-06 11:45:28.996: W/System.err(30433):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-06 11:45:28.996: W/System.err(30433):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-06 11:45:28.996: W/System.err(30433):    at com.example.testgallery.gameOver.postData(gameOver.java:90)
09-06 11:45:28.996: W/System.err(30433):    at com.example.testgallery.gameOver$1.onClick(gameOver.java:71)
09-06 11:45:28.996: W/System.err(30433):    at android.view.View.performClick(View.java:4240)
09-06 11:45:28.996: W/System.err(30433):    at android.view.View$PerformClick.run(View.java:17721)
09-06 11:45:28.996: W/System.err(30433):    at android.os.Handler.handleCallback(Handler.java:730)
09-06 11:45:28.996: W/System.err(30433):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-06 11:45:28.996: W/System.err(30433):    at android.os.Looper.loop(Looper.java:137)
09-06 11:45:28.996: W/System.err(30433):    at android.app.ActivityThread.main(ActivityThread.java:5103)
09-06 11:45:28.996: W/System.err(30433):    at java.lang.reflect.Method.invokeNative(Native Method)
09-06 11:45:28.996: W/System.err(30433):    at java.lang.reflect.Method.invoke(Method.java:525)
09-06 11:45:28.996: W/System.err(30433):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-06 11:45:28.996: W/System.err(30433):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-06 11:45:28.996: W/System.err(30433):    at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

  • 你能发布你的 logcat 输出吗,你的代码本身并不能提供足够的帮助。是的,您应该将您的网络代码放在AsyncTask 中,否则StrictMode 将终止请求。
  • 好的,我加了......
  • 是的,NetworkOnMainThread 异常是问题所在。使用AsyncTask。看看下面的答案。

标签: php android json http


【解决方案1】:

是的,您绝对应该使用AsyncTask 来做到这一点! 在您的代码中,您可以创建一个扩展 AsyncTask 的类:

public class LoadData extends AsyncTask<String, Integer, JSONObject> {

在这个类中,您将覆盖 2 个方法:doInBackground,基本上将执行您在 onClick() 方法中的代码,以及 onPostExecute(),它将对服务器的响应进行一些处理。

protected JSONObject doInBackground(String... urls) {
    // Build your json objects and create an HttpPost that will contact the url in urls[0]
    // then return a JSONObject containing the response
}

protected void onPostExecute(JSONObject result) {
    // parse the content of result to analyze the response of the server
}

然后在您的onClick 方法中,您可以创建此类的一个实例并在其上调用execute,并传递您要访问的网址:

LoadData loadData = new LoadData(getApplicationContext());
loadData.execute(your_url);

编辑

我记得前段时间为另一个人写过类似的代码,你可以查看这篇文章以获取另一个示例:getting value using JSON nullpointer

【讨论】:

    【解决方案2】:

    您应该使用 AsyncTask 来发送数据。我不知道您的 php 页面,但是我将尝试解释如何使用 JSON 从 android 向服务器发送数据(如果您有任何其他问题,请参阅本教程 http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/)。您将三个值作为 POST 请求发送到服务器。我认为您的 php 文件应该接收三个变量并将它们插入数据库,然后相应地发回数据。

    您的 php 文件(我假设您要将这些值插入到名为 Details 的数据库中,该数据库具有三列 timestamp,name,value,然后告诉应用用户数据是否已插入.)

    插入.php

    <?php
    
        //connect to your database
    
        //declare an array to encode your response
        $arr = array();
    
        if((isset($_POST["timestamp"]))&&(isset($_POST["name"]))&&(isset($_POST["value"])))
         {
           $time = $_POST["timestamp"];
           $name = $_POST["name"];
           $value = $_POST["value"];
           $query = "insert into Details(timestamp,name,value) values '$time','$name','$value'";
           $result = mysql_query($result);
             if ($result) {
          // successfully inserted into database
             $arr["success"] = 1;
             $arr["message"] = "Data successfully inserted.";
    
        // echoing JSON response
            echo json_encode($arr);
            } else {
            // failed to insert row
             $arr["success"] = 0;
             $arr["message"] = "An error occurred.";
    
            // echoing JSON response
            echo json_encode($arr);
           }
           } else {
           // required field is missing
           $arr["success"] = 0;
           $arr["message"] = "Required field(s) is missing";
    
          // echoing JSON response
          echo json_encode($arr);
          }
    ?> 
    

    您的 gameOver 类必须有一个子类,该子类必须扩展 AsyncTask 并进行 JSON 插入。

    gameOver 活动

          public class gameOver extends Activity {
        //TextView hiscores;
       JSONParser jsonParser; 
       protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gameover);
    
    final Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {
        @Override 
        public void onClick(View v) {
            // Perform action on click 
    
            Toast.makeText(gameOver.this, "button was pressed",
                    Toast.LENGTH_SHORT).show();
            new Insert().execute();
    
        } 
    });      
    } 
    
    class Insert extends AsyncTask<String, String, String>
    
    {
    
    @Override
        protected void onPreExecute() {
          super.onPreExecute();
          pDialog = new ProgressDialog(gameOver.this);
          pDialog.setMessage("Inserting Details..");
          pDialog.setIndeterminate(false);
          pDialog.setCancelable(true);
          pDialog.show();
      }
    
    @Override
    protected String doInBackground(String... arg0) {
    
        jsonParser = new JSONParser();
    
        //Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("timestamp",1351181576.64078));
        params.add(new BasicNameValuePair("name","engine_speed"));
        params.add(new BasicNameValuePair("value", 714.0));
    
        //getting JSON Object
        JSONObject json = jsonParser.makeHttpRequest("<your-domain-name>/insert.php", "POST", params);
    
        //Log.d("JSON:",json.toString());
    
        try
        {
            success = json.getInt("success");
    
            if(success == 1){
                Log.d("Query","Data Successfully inserted");
            }else{
                Log.d("Query","Unsuccessful in data submition");
            }
        }catch(JSONException e){
            Log.d("JSON:","EXCEPTION");
        }
    
        return null;
    }    
    

    上面提到的JSONParser类是

    package <your-package-name>;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    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.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    public class JSONParser {
    
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    
    // constructor
    public JSONParser() {
    
    }
    
    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
    
        // Making HTTP request
        try {
    
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
    
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
    
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
    
        // return JSON String
        return jObj;
    
    }
    }
    

    【讨论】:

    • 谢谢!我必须在 gameOver 活动中添加两个右大括号,而 BasicNameValuePair 显然只接受字符串,所以我将它们全部设为字符串并且它起作用了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2018-05-11
    • 2013-03-10
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多