Android POST请求无法正常工作

时间:2018-07-25 17:46:39

标签: java android http post

我正在使用以下方法通过发布请求从服务器获取时间。

    String result = "";
    URL url = null;
    InputStream stream = null;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://192.168.118.2/myapi");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);

        String data = URLEncoder.encode("time", "UTF-8")
                + "=" + URLEncoder.encode("Submit", "UTF-8");

        urlConnection.connect();

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(data);
        wr.flush();

        stream = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
        String line = "";
        while((line = reader.readLine()) != null)
            result += line;

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    Toast.makeText(this, result, Toast.LENGTH_SHORT).show();

这是php脚本

<?php
if(isset($_POST["time"]))
    echo "Time";
else
    echo "Invalid Request";

但是当我调用post方法时,我得到的结果为“无效请求”。 我几乎搜索了每个stackoverflow线程,但是它们都不起作用,我真的很想知道是什么问题。

2 个答案:

答案 0 :(得分:0)

一些尝试。

1)将以下内容添加到清单中。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

2)更改您的PHP文件

<?php  
    $time   = urldecode($_POST['time']);        
    if($time === NULL) {
        echo "invalid";       
    } else {
        echo "time";
    }
?>

答案 1 :(得分:0)

我通过以下更改解决了该问题;

data = "time=Submit";
...
...
...
url = new URL("http://192.168.118.2/myapi/index.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setInstanceFollowRedirects( false );
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty( "charset", "utf-8");
urlConnection.setRequestProperty( "Content-Length", Integer.toString( data.getBytes().length ));
urlConnection.setUseCaches( false );
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(1000);
...
...
...