Android Http POST请求doesen工作

时间:2018-03-15 16:37:44

标签: java android http post

我有这个Android代码:

package com.example.webtestconnection;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    private Button login;
    private EditText username, password;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        login = (Button) findViewById(R.id.ok);
        username = (EditText) findViewById(R.id.name);
        password = (EditText) findViewById(R.id.password);

        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String   mUsername = username.getText().toString();
                String  mPassword = password.getText().toString();

                tryLogin(mUsername, mPassword);
            }
        });
    }

    protected void tryLogin(String mUsername, String mPassword)
    {
        HttpURLConnection connection;
        OutputStreamWriter request = null;

        URL url = null;
        String response = null;
        String parameters = "username="+mUsername+"&password="+mPassword;

        try
        {
            url = new URL("http://welovelamacompany.altervista.org/test2.php");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            // Response from server after login process will be stored in response variable.
            response = sb.toString();
            // You can perform UI operations here
            Toast.makeText(this,"Message from Server: \n"+ response, Toast.LENGTH_LONG).show();
            isr.close();
            reader.close();

        }
        catch(IOException e)
        {
            // Error
        }
    }
}

这是php页面代码:

<?php
//impostazioni server phpmyadmin per poter accedere al db
    $servername = "servername";
    $username = "username";
    $password = "password";
    $databasename = "my_databasename";
    $Nome_Giocatore = $_POST['username'];
    $PasswordGiocatore = $_POST['password'];
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$databasename", $username, $password);
        //imposto una modalità di eccezzione errore
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //stampo che la connessione è riuscita
        $sql=$conn->query("SELECT Password_Giocatore FROM Giocatori WHERE Nome_Giocatore=\"$Nome_Giocatore\"");
        $control = $sql->fetch();
        $controllo=$control['Password_Giocatore'];
        if (password_verify($PasswordGiocatore, $controllo)){
            echo "Success";
        } else {
            echo "Error";
        }
        $conn->exec($sql);
    } catch(PDOException $e){
                    //stampo che la connessione è fallita e l'errore che ha causato il fallimento
                    echo "Qualcosa è andato storto :(. Errore: <br/>".$e->getMessage();
                }
    $conn = null;
?>

但是当我运行它时,它会给我这个错误:

  

E / AndroidRuntime:致命异常:主要                     处理:com.example.webtestconnection,PID:23550                     android.os.NetworkOnMainThreadException                         在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)                         at java.net.InetAddress.lookupHostByName(InetAddress.java:385)                         at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)                         at java.net.InetAddress.getAllByName(InetAddress.java:214)                         在com.android.okhttp.internal.Dns $ 1.getAllByName(Dns.java:28)                         在com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)                         在com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)                         在com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390)                         在com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343)                         在com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)                         在com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)                         在com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)                         在com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)                         在com.example.webtestconnection.MainActivity.tryLogin(MainActivity.java:62)                         at com.example.webtestconnection.MainActivity $ 1.onClick(MainActivity.java:40)                         在android.view.View.performClick(View.java:4633)                         在android.view.View $ PerformClick.run(View.java:19270)                         在android.os.Handler.handleCallback(Handler.java:733)                         在android.os.Handler.dispatchMessage(Handler.java:95)                         在android.os.Looper.loop(Looper.java:136)                         在android.app.ActivityThread.main(ActivityThread.java:5476)                         at java.lang.reflect.Method.invokeNative(Native Method)                         在java.lang.reflect.Method.invoke(Method.java:515)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1283)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)                         在dalvik.system.NativeStart.main(本地方法)

为什么呢?我该如何解决?谢谢你的帮助

P.S。我在清单中有互联网许可

2 个答案:

答案 0 :(得分:2)

请使用AsyncTask进行API调用,因为您在MainThread上调用它而获得异常。

class LoginTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected YourResponse doInBackground(String... urls) {
        try {
             URL url = new URL(urls[0]);
            //your login code
        } catch (Exception e) {
            this.exception = e;
        } 
    }
    protected void onPostExecute(YourResponse response) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

并在代码中添加此行

new LoginTask().execute(url);

<强> EDITED 您可以在图书馆下方进行网络通话,更轻松,优化网络通话

  1. Retrofit
  2. Volley

答案 1 :(得分:0)

您正尝试在主线程上运行http连接。这在Android中是绝对禁止的,因为你破坏了应用程序的响应能力。您应该将连接运行到AsyncTask