添加帖子时,Android Http Post无效

时间:2015-04-23 22:25:59

标签: php android httpurlconnection

我只是尝试使用HttpUrlConnection通过我的android模拟器添加评论帖,但它没有通过。我有我的互联网权限集和PHP文件工作,因为我可以在浏览器上成功提交。这是我的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_comment);

    MyTask tasker= new MyTask();
    tasker.execute();

}

private class MyTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... params) {
        adcomment = (Button) findViewById(R.id.adcomment);

        adcomment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    url = new URL("http://10.0.2.2:8080/addcomment.php");
                    String param = "user=bb&title=ss&message=uu";
                    byte[] postData = param.getBytes(Charset.forName("UTF-8"));
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestMethod("POST");
                    conn.setFixedLengthStreamingMode(param.getBytes().length);
                    (conn).setFixedLengthStreamingMode(param.length());
                    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                    wr.write(postData);
                    Toast.makeText(AddComment.this, "It worked", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(AddComment.this, "It failed", Toast.LENGTH_LONG).show();
                }
            }

        });

        return null;
    }
}

应用程序不会崩溃它只是转到Catch语句,并且此特定行显示在调试中 DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

PHP文件是一个简单的插入语句

<?php

 require("configExo.php");

     if (!empty($_POST)) {
  // initial query
$query = "INSERT INTO comments ( username, title, message ) VALUES  ( :user, :title, :message ) ";

//Update query
$query_params = array(
    ':user' => $_POST['username'],
    ':title' => $_POST['title'],
    ':message' => $_POST['message']
);

//execute query
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    $response["success"] = 0;
    $response["message"] = "Database Error. Couldn't add post!";
    die(json_encode($response));
}


$response["message"] = "Username Successfully Added!";
echo json_encode($response);

}
else {
?>
  <h1>Add Comment</h1>
 <form action="addcomment.php" method="post">
    Username:<br />
    <input type="text" name="username" placeholder="username" />
    <br /><br />
    Title:<br />
    <input type="text" name="title" placeholder="post title" />
    <br /><br />
    Message:<br />
    <input type="text" name="message" placeholder="post message" />
    <br /><br />
    <input type="submit" value="Add Comment" />
  </form>
  <?php
   }

  ?>

这是我最新实例的Logcat

04-23 22:43:03.374        78-78/? E/BatteryService﹕ usbOnlinePath not found
04-23 22:43:03.374        78-78/? E/BatteryService﹕ batteryVoltagePath not found
04-23 22:43:03.374        78-78/? E/BatteryService﹕ batteryTemperaturePath not found
04-23 22:43:03.505        78-93/? A/BatteryStatsImpl﹕ problem reading network stats
    java.lang.IllegalStateException: problem parsing idx 1
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:300)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:250)
            at com.android.internal.os.BatteryStatsImpl.getNetworkStatsDetailGroupedByUid(BatteryStatsImpl.java:5734)
            at com.android.internal.os.BatteryStatsImpl.access$100(BatteryStatsImpl.java:76)
            at com.android.internal.os.BatteryStatsImpl$Uid.computeCurrentTcpBytesReceived(BatteryStatsImpl.java:2457)
            at com.android.internal.os.BatteryStatsImpl$Uid.getTcpBytesReceived(BatteryStatsImpl.java:2446)
            at com.android.internal.os.BatteryStatsImpl.writeSummaryToParcel(BatteryStatsImpl.java:5437)
            at com.android.internal.os.BatteryStatsImpl.writeLocked(BatteryStatsImpl.java:4836)
            at com.android.internal.os.BatteryStatsImpl.writeAsyncLocked(BatteryStatsImpl.java:4818)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:1492)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:151)
            at com.android.server.am.ActivityManagerService$AThread.run(ActivityManagerService.java:1393)
     Caused by: java.io.FileNotFoundException: /proc/net/xt_qtaguid/stats: open failed: ENOENT (No such file or directory)
            at libcore.io.IoBridge.open(IoBridge.java:406)
            at java.io.FileInputStream.<init>(FileInputStream.java:78)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:269)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:250)
            at com.android.internal.os.BatteryStatsImpl.getNetworkStatsDetailGroupedByUid(BatteryStatsImpl.java:5734)
            at com.android.internal.os.BatteryStatsImpl.access$100(BatteryStatsImpl.java:76)
            at com.android.internal.os.BatteryStatsImpl$Uid.computeCurrentTcpBytesReceived(BatteryStatsImpl.java:2457)
            at com.android.internal.os.BatteryStatsImpl$Uid.getTcpBytesReceived(BatteryStatsImpl.java:2446)
            at com.android.internal.os.BatteryStatsImpl.writeSummaryToParcel(BatteryStatsImpl.java:5437)
            at com.android.internal.os.BatteryStatsImpl.writeLocked(BatteryStatsImpl.java:4836)
            at com.android.internal.os.BatteryStatsImpl.writeAsyncLocked(BatteryStatsImpl.java:4818)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:1492)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:151)
            at com.android.server.am.ActivityManagerService$AThread.run(ActivityManagerService.java:1393)
     Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
            at libcore.io.Posix.open(Native Method)
            at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
            at libcore.io.IoBridge.open(IoBridge.java:390)
            at java.io.FileInputStream.<init>(FileInputStream.java:78)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:269)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:250)
            at com.android.internal.os.BatteryStatsImpl.getNetworkStatsDetailGroupedByUid(BatteryStatsImpl.java:5734)
            at com.android.internal.os.BatteryStatsImpl.access$100(BatteryStatsImpl.java:76)
            at com.android.internal.os.BatteryStatsImpl$Uid.computeCurrentTcpBytesReceived(BatteryStatsImpl.java:2457)
            at com.android.internal.os.BatteryStatsImpl$Uid.getTcpBytesReceived(BatteryStatsImpl.java:2446)
            at com.android.internal.os.BatteryStatsImpl.writeSummaryToParcel(BatteryStatsImpl.java:5437)
            at com.android.internal.os.BatteryStatsImpl.writeLocked(BatteryStatsImpl.java:4836)
            at com.android.internal.os.BatteryStatsImpl.writeAsyncLocked(BatteryStatsImpl.java:4818)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:1492)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:151)
            at com.android.server.am.ActivityManagerService$AThread.run(ActivityManagerService.java:1393)
04-23 22:43:03.535        78-93/? E/AndroidRuntime﹕ Error reporting WTF
    java.lang.NullPointerException
            at com.android.internal.os.RuntimeInit.wtf(RuntimeInit.java:345)
            at android.util.Log$1.onTerribleFailure(Log.java:103)
            at android.util.Log.wtf(Log.java:278)
            at com.android.internal.os.BatteryStatsImpl.getNetworkStatsDetailGroupedByUid(BatteryStatsImpl.java:5738)
            at com.android.internal.os.BatteryStatsImpl.access$100(BatteryStatsImpl.java:76)
            at com.android.internal.os.BatteryStatsImpl$Uid.computeCurrentTcpBytesReceived(BatteryStatsImpl.java:2457)
            at com.android.internal.os.BatteryStatsImpl$Uid.getTcpBytesReceived(BatteryStatsImpl.java:2446)
            at com.android.internal.os.BatteryStatsImpl.writeSummaryToParcel(BatteryStatsImpl.java:5437)
            at com.android.internal.os.BatteryStatsImpl.writeLocked(BatteryStatsImpl.java:4836)
            at com.android.internal.os.BatteryStatsImpl.writeAsyncLocked(BatteryStatsImpl.java:4818)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:1492)
            at com.android.server.am.ActivityManagerService.<init>(ActivityManagerService.java:151)
            at com.android.server.am.ActivityManagerService$AThread.run(ActivityManagerService.java:1393)
04-23 22:43:04.104        78-87/? E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at java.io.FileInputStream.<init>(FileInputStream.java:80)
            at com.android.server.pm.UserManager.readUserList(UserManager.java:114)
            at com.android.server.pm.UserManager.<init>(UserManager.java:81)
            at com.android.server.pm.UserManager.<init>(UserManager.java:85)
            at com.android.server.pm.PackageManagerService.<init>(PackageManagerService.java:923)
            at com.android.server.pm.PackageManagerService.main(PackageManagerService.java:833)
            at com.android.server.ServerThread.run(SystemServer.java:163)
04-23 22:43:08.134       78-121/? E/SoundPool﹕ error loading /system/media/audio/ui/Lock.ogg
04-23 22:43:08.134       78-121/? E/SoundPool﹕ error loading /system/media/audio/ui/Unlock.ogg
04-23 22:43:08.235       78-126/? E/EventHub﹕ could not get driver version for /dev/input/mouse0, Not a typewriter
04-23 22:43:08.235       78-126/? E/EventHub﹕ could not get driver version for /dev/input/mice, Not a typewriter
04-23 22:43:08.414        33-56/? E/CommandListener﹕ Failed to open /proc/sys/net/ipv6/conf/wlan0/disable_ipv6: No such file or directory
04-23 22:43:08.414        78-92/? E/WifiStateMachine﹕ Failed to disable IPv6: java.lang.IllegalStateException: Unable to communicate to native daemon for disabling ipv6
04-23 22:43:08.464        78-92/? E/MobileDataStateTracker﹕ default: Ignoring feature request because could not acquire PhoneService
04-23 22:43:08.464        78-92/? E/MobileDataStateTracker﹕ default: Could not enable APN type "default"
04-23 22:43:12.955      158-229/? E/ActivityThread﹕ Failed to find provider info for com.android.inputmethod.latin.dictionarypack
04-23 22:43:13.015      158-229/? E/BinaryDictionaryGetter﹕ Could not find a dictionary pack
04-23 22:43:19.748       78-129/? A/NetworkStats﹕ problem reading network stats
    java.lang.IllegalStateException: problem parsing idx 1
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:300)
            at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1282)
            at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:831)
            at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:743)
            at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:721)
            at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
            at com.android.server.net.NetworkStatsService$8.handleMessage(NetworkStatsService.java:1633)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:137)
            at android.os.HandlerThread.run(HandlerThread.java:60)
     Caused by: java.io.FileNotFoundException: /proc/net/xt_qtaguid/stats: open failed: ENOENT (No such file or directory)
            at libcore.io.IoBridge.open(IoBridge.java:406)
            at java.io.FileInputStream.<init>(FileInputStream.java:78)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:269)
            at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1282)
            at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:831)
            at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:743)
            at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:721)
            at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
            at com.android.server.net.NetworkStatsService$8.handleMessage(NetworkStatsService.java:1633)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:137)
            at android.os.HandlerThread.run(HandlerThread.java:60)
     Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
            at libcore.io.Posix.open(Native Method)
            at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
            at libcore.io.IoBridge.open(IoBridge.java:390)
            at java.io.FileInputStream.<init>(FileInputStream.java:78)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:269)
            at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1282)
            at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:831)
            at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:743)
            at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:721)
            at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
            at com.android.server.net.NetworkStatsService$8.handleMessage(NetworkStatsService.java:1633)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:137)
            at android.os.HandlerThread.run(HandlerThread.java:60)
04-23 22:43:24.138       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/Effect_Tick.ogg
04-23 22:43:24.138       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/Effect_Tick.ogg
04-23 22:43:24.138       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/Effect_Tick.ogg
04-23 22:43:24.138       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/Effect_Tick.ogg
04-23 22:43:24.138       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/Effect_Tick.ogg
04-23 22:43:24.149       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/KeypressStandard.ogg
04-23 22:43:24.149       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/KeypressSpacebar.ogg
04-23 22:43:24.149       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/KeypressDelete.ogg
04-23 22:43:24.149       78-141/? E/SoundPool﹕ error loading /system/media/audio/ui/KeypressReturn.ogg
04-23 22:43:25.839       78-129/? A/NetworkStats﹕ problem reading network stats
    java.lang.IllegalStateException: problem parsing idx 1
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:300)
            at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1282)
            at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:831)
            at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:743)
            at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:721)
            at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
            at com.android.server.net.NetworkStatsService$1.onReceive(NetworkStatsService.java:612)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
            at android.os.Handler.handleCallback(Handler.java:605)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.os.HandlerThread.run(HandlerThread.java:60)
     Caused by: java.io.FileNotFoundException: /proc/net/xt_qtaguid/stats: open failed: ENOENT (No such file or directory)
            at libcore.io.IoBridge.open(IoBridge.java:406)
            at java.io.FileInputStream.<init>(FileInputStream.java:78)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:269)
            at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1282)
            at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:831)
            at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:743)
            at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:721)
            at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
            at com.android.server.net.NetworkStatsService$1.onReceive(NetworkStatsService.java:612)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
            at android.os.Handler.handleCallback(Handler.java:605)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.os.HandlerThread.run(HandlerThread.java:60)
     Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
            at libcore.io.Posix.open(Native Method)
            at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
            at libcore.io.IoBridge.open(IoBridge.java:390)
            at java.io.FileInputStream.<init>(FileInputStream.java:78)
            at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:269)
            at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1282)
            at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:831)
            at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:743)
            at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:721)
            at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
            at com.android.server.net.NetworkStatsService$1.onReceive(NetworkStatsService.java:612)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
            at android.os.Handler.handleCallback(Handler.java:605)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.os.HandlerThread.run(HandlerThread.java:60)
04-23 22:43:30.578      320-344/? E/DefaultVoicemailNotifier﹕ No voicemails to notify about: clear the notification.

1 个答案:

答案 0 :(得分:1)

看起来问题是你的OnClickListenerdoInBackground内。

OnClickListener移至onCreate(),并在点击该按钮时启动AsyncTask

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_comment);

       adcomment = (Button) findViewById(R.id.adcomment);

       adcomment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 //Start AsyncTask
                 MyTask tasker= new MyTask();
                 tasker.execute();
            }

      });
   }

   private class MyTask extends AsyncTask<String, String, String> {


    @Override
    protected String doInBackground(String... params) {

         try {
                url = new URL("http://10.0.2.2:8080/addcomment.php");
                String param = "user=bb&title=ss&message=uu";
                byte[] postData = param.getBytes(Charset.forName("UTF-8"));
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");
                conn.setFixedLengthStreamingMode(param.getBytes().length);
                (conn).setFixedLengthStreamingMode(param.length());
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr.write(postData);
                Toast.makeText(AddComment.this, "It worked", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(AddComment.this, "It failed", Toast.LENGTH_LONG).show();
            }


        return null;
    }
}