dongyi8383 2017-01-01 08:33
浏览 85
已采纳

无法将POST从android发送到php

I'm new to android and I tried to make a simple login test with android http post and php, though I'm unable to send posts with the following code:

package com.yagami.boook.classify;

import android.app.ProgressDialog;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by allen on 2017/1/1.
 */

public class GetUserInfo extends AsyncTask<String, Integer, String> {

//    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
//        dialog = ProgressDialog.show(MainActivity.class, "Retrieving User Data", "Please wait...", true);
    }

    @Override
    protected void onPostExecute(String aString) {
        super.onPostExecute(aString);
//        dialog.dismiss();
    }

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

        HttpURLConnection connection;
        OutputStreamWriter request = null;
        URL url = null;
        Log.d("A","A");

        try {


            url = new URL("http://localhost/login.php");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            Log.d("B","B");

            request = new OutputStreamWriter(connection.getOutputStream());
            Log.d("C","C");
            request.write(strings[0]);
            request.flush();
            request.close();

            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);

            String response = reader.readLine();
            isr.close();
            reader.close();

            return response;
        } catch (IOException e) {
            // Error
        }
        return null;
    }
}

Here is the php file, I tried to print a txt file so I would know if I received anything:

<?php
    $email = $_POST['username'];
    $password = $_POST['password'];

//  echo $username."<br>";
//  echo $password."<br>";

    $connect = mysql_connect("localhost" , "root" , "112233");
    mysql_select_db("classify", $connect);
    $data = mysql_query("select * from users where email = '$email'");
    $row = mysql_fetch_row($data);

//  echo $row[2];

    if($row[2] == $password) echo "pass";
    else echo "nopass";

    $fp = fopen('xxx.txt', 'w');
    fwrite($fp , "abc");
    fclose($fp);

?>

Here's the log, I added some Log.d into the code so that it would be more easy to understand what's happening. (As you can see the Log.d("C", "C") isn't showing up)

01/01 17:22:50: Launching app
$ adb push C:\Users\allen\Desktop\MyApplication\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.allen.myapplication
$ adb shell pm install -r "/data/local/tmp/com.example.allen.myapplication"
Success


$ adb shell am start -n "com.example.allen.myapplication/com.example.allen.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 3148 on device Nexus_5X_API_25 [emulator-5554]
W/System: ClassLoader referenced unknown path: /data/app/com.example.allen.myapplication-2/lib/x86
I/InstantRun: Instant Run Runtime started. Android package is com.example.allen.myapplication, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.example.allen.myapplication-2/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
E/EGL_emulation: tid 3195: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x99477440, error=EGL_BAD_MATCH
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
D/NetworkSecurityConfig: No Network Security Config specified, using platform default

01/01 17:24:54: Launching app
W/System: ClassLoader referenced unknown path: /data/data/com.example.allen.myapplication/lib
E/EGL_emulation: tid 3195: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9947d420, error=EGL_BAD_MATCH
E/EGL_emulation: tid 3195: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x98d37ba0, error=EGL_BAD_MATCH
Hot swapped changes, activity restarted
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
D/A: A
D/B: B
D/A: A
D/B: B

Have already searched the whole google for debugging but didn't find anything useful, hope it isn't a stupid mistake. Also please notify me if more information is needed.

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • duanchi8836 2017-01-01 10:14
    关注

    You are trying to access http://localhost/ from your device or emulator, but your actual web server runs somewhere else. So, for your device this web server is not a localhost.

    To make this work, you need to make sure that the device is connected to the same network as your web server, and that the web server is accessible from your device (probable firewall issues, etc.). You then need to find out the IP address of your host inside the network, e.g. 192.168.1.42, and use that IP address in your android code:

    // use your valid IP address instead
    url = new URL("http://192.168.1.42/login.php");
    

    With this connection, the device will look for a provided IP in your network, and access it, if it is available. Also, note that your IP will probably change, so you'll need to figure out how to make it static.

    More on accessing localhost from an Android device here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算