2015-11-02 62 views
1

我正在嘗試使用this文檔的參考進行發佈請求。但問題是另一端的PHP開發人員無法接收參數的值,因此無法發送正確的響應。我在這裏錯過了什麼嗎?URLConnection和POST方法android

//編輯;

我正在發出一個HTTP Post請求。正如你可以看到下面的代碼。我將參數和參數(location_id = 3)寫入輸出流。我也粘貼了我一直在使用的PHP代碼。現在的問題是:

在PHP代碼中沒有收到參數值(它是3),所以我得到一個被else塊包圍的響應。所以,我只是想知道是否有在Android的代碼錯誤或PHP代碼

@覆蓋 保護布爾doInBackground(字符串... 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爲字符串

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


?> 
+0

只是一個建議:你有沒有考慮過使用可以爲你做95%的東西的東西?例如,POST + JSON聽起來像「REST Service」,爲此Spring-Web提供了一些很棒的工具(但可能有幾十個其他的庫) –

+0

@FlorianSchaetz:請你詳細說明一下,我希望你正在回答android的解決方案。 –

+0

'另一端的PHP開發人員無法接收參數的值。那麼開始告訴他如何接收哪個參數。否則,我們必須猜測,您可以發佈您的PHP腳本。 – greenapps

回答

1

刪除:

urlConnection.setChunkedStreamingMode(0); 

您可以使用一個緩衝的作家,因此只能緩衝,而不是寫。 要強制所有被寫入:

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

然後索要響應代碼。並且不要將響應碼稱爲狀態碼。

writeToOutputStream() ???多麼可怕的名字。該函數不寫入輸出流。它只是產生一個文本字符串。

+0

是工作,但爲什麼我們刪除了setChunkedStreamingMode(0)。你能否詳細說明一下。 –

0

對於Android,我會建議使用庫像Spring-Android

Spring-Android包含一個RestTemplate類,這是一個非常有效的REST客戶端。例如,一個簡單的POST請求將...

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

要創建的JSON字符串,我建議像傑克遜庫,它應該工作正常,在Android上看到例如here。不確定Jackson是否像Spring-Web一樣在Spring-Android中集成了良好的功能,但無論如何,使用它來手動創建Json字符串應該工作得很好。

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'] 
+0

我沒有看到那幫助,因爲我已經在使用concat。但仍試圖確保結果沒有return.Thanx –