gpt4 book ai didi

java - Android Http POST 请求不起作用

转载 作者:行者123 更新时间:2023-12-02 02:15:52 26 4
gpt4 key购买 nike

我有这个 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: FATAL EXCEPTION: main Process: com.example.webtestconnection, PID: 23550 android.os.NetworkOnMainThreadException at 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) at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28) at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216) at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122) at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390) at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343) at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289) at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345) at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89) at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197) at com.example.webtestconnection.MainActivity.tryLogin(MainActivity.java:62) at com.example.webtestconnection.MainActivity$1.onClick(MainActivity.java:40) at android.view.View.performClick(View.java:4633) at android.view.View$PerformClick.run(View.java:19270) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5476) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) at dalvik.system.NativeStart.main(Native Method)

为什么?我该如何修复它?感谢您的帮助

附注我在 list 中拥有互联网权限

最佳答案

请使用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);

已编辑您可以使用以下网络调用库,更轻松地针对网络调用进行优化

  1. Retrofit
  2. Volley

关于java - Android Http POST 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49304798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com