URLConnection和POST方法android

时间:2015-11-02 14:40:09

标签: java android json parsing

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

//编辑;

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

在PHP代码中没有收到参数值(即3),因此我得到一个被else块包围的响应。所以我只想知道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到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 CODE

<?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";
    }


?>

3 个答案:

答案 0 :(得分:1)

卸下:

urlConnection.setChunkedStreamingMode(0);

您使用缓冲编写器,因此它只能缓冲而不是写入。 强迫所有人写完:

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

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

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

答案 1 :(得分:0)

对于Android,我建议使用像Spring-Android这样的库。

Spring-Android包含一个RestTemplate类,它是一个非常有效的REST-Client。例如,一个简单的POST请求将是......

myRestTemplate.exchange("http://www.example.net", HttpMethod.POST, new HttpEntity( ...some JSON string ...), String.class );

要创建JSON字符串,我建议像Jackson一样的库,它应该可以在Android上正常工作,例如参见here。不确定Jackson是否像在Spring-Web中一样在Spring-Android中集成,但无论如何,使用它来手动创建Json Strings应该可以正常工作。

答案 2 :(得分:0)

用于发布方法 首先创建一个字符串构建器

StringBuilder strbul=new StringBuilder();

然后追加像

这样的数据
strbul.append("name=sangeet&state=kerala");

然后写入输出流,如

httpurlconnection.getOutput().write(strbul.toString().getBytes("UTF-8"));

php脚本将在

上收到该数据
$_POST['name'] and $_POST['state']