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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化