java - URLConnection 和 POST 方法 android

标签 java android json parsing

我正在尝试使用 this 的引用发出发布请求文档。但问题是另一端的 PHP 开发人员无法接收参数值,因此无法发送正确的响应。我在这里遗漏了什么吗?

//编辑 ;

我正在发出 HTTP Post 请求。如您所见,下面的代码。我正在将参数和参数 (location_id=3) 写入输出流。我还粘贴了我一直在使用的 PHP 代码。现在的问题是:

PHP 代码未收到参数值(为 3),因此我收到的响应被 else block 包围。所以我只想知道是android代码还是php代码有错误

@覆盖 protected Boolean doInBackground(String... params) {

        Log.d(Constants.LOG_TAG,Constants.FETCH_ALL_THEMES_ASYNC_TASK);
        Log.d(Constants.LOG_TAG," The url to be fetched "+params[0]);

        try {
            url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

//                 /* optional request header */
//            urlConnection.setRequestProperty("Content-Type", "application/json");
//
//                /* optional request header */
//            urlConnection.setRequestProperty("Accept", "application/json");

                /* for Get request */
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod("POST");

            List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("location_id",params[1]));

            outputStream = urlConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(writeToOutputStream(nameValuePairs));


            int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
            if (statusCode == 200) {
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                response = convertInputStreamToString(inputStream);
                Log.d(Constants.LOG_TAG, " The response is " + response);



                return true;
            }
            else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if(inputStream != null){

                    inputStream.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return false;

    }

//这里是 writeToOutputStream 的代码

public String writeToOutputStream(List<BasicNameValuePair> keyValuePair)throws UnsupportedEncodingException{

    String result="";
    boolean firstTime = true;

    for(BasicNameValuePair pair : keyValuePair){


        if(firstTime){

            firstTime = false;
        }
        else{

            result = result.concat("&");

        }

        result = result + URLEncoder.encode(pair.getKey(), "UTF-8");
        result = result + "=";
        result =  result+ URLEncoder.encode(pair.getValue(),"UTF-8");

    }

    Log.d(Constants.LOG_TAG," The result is "+result);
    return result;

}

//这里是convertInputStream to String的代码

public String convertInputStreamToString(InputStream is) throws IOException {

        String line="";
        String result="";
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

        while((line = bufferedReader.readLine()) != null){

            Log.d(Constants.LOG_TAG," The line value is "+line);
            result += line;

        }

            /* Close Stream */
        if(null!=inputStream){
            inputStream.close();
        }

        return result;
    }

这是PHP代码

<?php
    include 'config.php';
    header ('Content-Type:application/json');

    if(isset($_POST['location_id']))
    {
        $id=$_POST['location_id'];

        $selectThemeQuery = mysql_query("select theme_id from location_theme where location_id='$id'",$conn) or die (mysql_error());
        $noRows = mysql_num_rows($selectThemeQuery);
         //echo "HI";
        if($noRows > 0)
        { 
            $result = array();
            while($row = mysql_fetch_assoc($selectThemeQuery))
            {
                $themeid = $row['theme_id'];
                //echo "HI";
                $selectNameQuery = mysql_query("select theme_name,theme_image from theme where theme_id='$themeid'",$conn) or die(mysql_error());
                $numRows = mysql_num_rows($selectNameQuery);

                if($numRows > 0)
                {
                    while($rows = mysql_fetch_assoc($selectNameQuery))
                    {
                        $name = $rows['theme_name'];
                        $image = $rows['theme_image'];

                        $result[] = array('theme_id'=>$themeid,'theme_name'=>$name, 'theme_image'=>$image);
                    }

                }

            }
            //echo json_encode($result);
                        echo json_encode("Hi");
        }
        else
        {
                $data2[] = array('Notice'=>false);
                echo json_encode($data2);
        }
    }
    else
    {
        echo "Not Proper Data";
    }


?>

最佳答案

删除:

urlConnection.setChunkedStreamingMode(0);

您使用缓冲写入器,因此它只能缓冲而不是写入。 强制全部写入:

bufferedWriter.write(writeToOutputStream(nameValuePairs));        
bufferedWriter.flush(); 

然后请求响应代码。并且不要将响应代码称为状态代码。

writeToOutputStream() ???多么可怕的名字。该函数不会写入输出流。它只是生成一个文本字符串。

关于java - URLConnection 和 POST 方法 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480141/

相关文章:

javascript - 如何使用方法保存和加载对象?

json - 有谁知道用于查找单词定义的 Web 服务能够以 JSON 返回结果吗?

java - 尝试将背景从白色更改为黑色,但无法运行此 timer() 方法,屏幕只有白色

java - 使浏览器获取修改后的 JS 和 CSS 文件

android - 如何检查电子邮件或手机是否已在 Firebase 中注册

json - 类似于 Json 的格式

java - 使用 java 执行和终止 OSX 的任何应用程序

java - 变量在一个实例中未使用,但在另一实例中未使用

java - setPressed 不起作用

带有 ListView fragment 和自定义 ListView 适配器的 Android 下拉刷新