如何使用 HttpUrlConnection 传递带有 POST 的参数

How to pass an argument with POST using HttpUrlConnection

编辑:我发现将 OutputStreamWriter 包装在 BufferedWriter 中是导致问题的原因,因此去掉了包装器,我的 POST 通过了。仍然想知道为什么 BufferedWriter 是原因。

我提前道歉,因为我刚刚开始自学所有关于数据库、应用程序与 server/database 之间的通信以及 php。

其他类似问题未提供答案。

在使用 HttpUrlConnection 从我的 android 应用程序到本地托管的 php 脚本制作一个简单的 POST 时,我无法辨别我遗漏了什么服务器。我需要从 android 应用程序中获取用户 ID,将其作为参数传递给 php 脚本,然后在名为 users 的数据库 table 中执行该 ID 的查找。我还想使用未弃用的方法和 classes。

我在 android 清单中包含了 Internet 权限。我正在使用 XAMPP,我已经验证我的服务器是 运行,如果我通过网络浏览器访问 url,我会得到我正在寻找的 JSON 响应.

我唯一的 logcat 消息是一个 IOException,它发生在写入输出流之后。 编辑: 具体的例外是"unexpected end of stream"

这是我的 AsyncTask 中的代码 class:

protected String doInBackground(String... params) {

    String userID = params[0];
    Pair<String, String> phpParameter = new Pair<>("userID", userID);
    String result = "";

    try {
        URL url = new URL("url of locally-hosted php script");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        // prepare request
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setFixedLengthStreamingMode(userID.getBytes("UTF-8").length);

        // upload request
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(phpParameter.first + "=" + phpParameter.second);
        writer.close();
        outputStream.close();

        // read response
        BufferedReader in = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()));

        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
        in.close();

        result = response.toString();

        // disconnect
        urlConnection.disconnect();
    } catch (MalformedURLException e) {
        Log.e("Malformed URL Exception", "Malformed URL Exception");
    } catch (IOException e) {
        Log.e("IOException", "IOException");
    }

    return result;
}

这是我在服务器上的 php 脚本。我还需要一些关于准备好的陈述的帮助,所以不要因为 'id = 1':

而打败我
<?php

mysql_connect("host","username","password");

mysql_select_db("Database");

print($_POST);

$sql = mysql_query("select * from users where id = 1");

while($row = mysql_fetch_assoc($sql))
$output[] = $row;

print(json_encode($output)); // this will print the output in json
mysql_close();

?>

兄弟,使用像 loopjs async httplib 这样的自定义库会更简单。查看您要执行的操作的代码示例,

你问为什么要使用它?所有异常和异步任务都在后台处理,使您的代码库更简单。

    AsyncHttpClient client = new AsyncHttpClient();
client.post(YOUR_POST_URL, new AsyncHttpResponseHandler() {

@Override
public void onStart() {
    // called before request is started
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
    // called when response HTTP status is "200 OK"
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
    // called when response HTTP status is "4XX" (eg. 401, 403, 404)
}

@Override
public void onRetry(int retryNo) {
    // called when request is retried
}
    });

从android到post:

public class HttpURLConnectionHandler
{
     protected String urlG = "http://192.168.43.98/yourdirectory/";
     public String sendText(String text)
    {
    try {
        URL url = new URL(urlG+"receiveData.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");

        // para activar el metodo post
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream wr = new DataOutputStream(
            conn.getOutputStream());
        wr.writeBytes("mydata="+text);
        wr.flush();
        wr.close();

        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
   }
   catch(Exception e){ return "error";}
   }
}

php 文件:

$x = $_POST['mydata'];
echo $x;  

看来我修好了!

我改了

BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(phpParameter.first + "=" + phpParameter.second);

OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(userID);

出于某种原因,将输出流写入器包装在缓冲写入器中的行为破坏了它。不知道为什么。

进行上述更改后,我收到一条错误消息,指出流需要 1 个字节但收到了 8 个字节,所以我只写了 userID,无论如何我都将其传递给 setFixedLengthStreamingMode。