php - 似乎无法将 JSONObject 从 android 发送到远程服务器

标签 php android json http

我一直在寻找一种方法将数据发送到远程服务器上的 php 页面,但似乎无法正常工作...我修改了 here 上类似问题的代码 但它仍然无法正常工作..我是否必须将 httppost 放在异步任务或其他东西中?我该怎么做?代码:

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)

最佳答案

是的,您绝对应该使用 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,传递您要访问的url:

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

编辑

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

关于php - 似乎无法将 JSONObject 从 android 发送到远程服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18661410/

相关文章:

php - 在 PHP echo 语句中添加多个类

php - MySQL数据库IP地址来自rackspace还是google cloud?

使用 ssl 的 PHP 连接到远程 mysql 通过命令工作,但不能在浏览器中工作

android - 如何使用实验性 Gradle 包含头文件?

javascript - 如何序列化Json javascript

javascript - 遍历 jquery json

c# Chart.Js 和 JSON 与 NewtonSoft

PHP 批量插入 foreach

android - 通过设备上安装的 android 应用程序进行调试的正确方法

android - 如何将带有源代码控制的Eclipse项目导入Android Studio而不将目录结构更改为Gradle目录结构?