如何使用HttpUrlConnection传递POST参数

时间:2015-07-09 17:15:36

标签: php android post httpurlconnection

编辑:我发现在BufferedWriter中包装OutputStreamWriter导致了问题,因此摆脱了包装器并且我的POST完成了。仍然想知道为什么BufferedWriter是原因。

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

其他类似的问题没有提供答案。

在使用我的Android应用程序中的HttpUrlConnection到本地托管服务器上的php脚本进行简单的POST时,我很难辨别出我所缺少的内容。我需要从android应用程序中获取用户ID,将其作为参数传递给php脚本,并在名为users的数据库表中执行该ID的查找。我还想使用未弃用的方法和类。

我在Android清单中包含了Internet权限。我正在使用XAMPP,我已经验证我的服务器正在运行,如果我通过Web浏览器访问该URL,我会收到我正在寻找的JSON响应。

我唯一的logcat消息是IOException,它在写入输出流之后发生。 编辑: 特定的例外情况是"流的意外结束"

以下是我的AsyncTask类中的代码:

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; = =&#39;

而打败我。
<?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();

?>

3 个答案:

答案 0 :(得分:1)

从android发布:

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;  

答案 1 :(得分:0)

enter image description here

兄弟,使用像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
}
    });

答案 2 :(得分:0)

看起来我修好了!

我改变了

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的。