2015-09-28 66 views
1

我想發佈一個字符串到php腳本。該腳本返回一個字符串,其中的值由分號分隔(如「hello; world」)。Android的httppost沒有結果

我爲這個字符串實現了一個測試,所以我可以在我的瀏覽器中測試它並且它可以工作。但我的應用程序沒有得到任何結果。

這裏是我的代碼

public class GetInformationForBarcode extends AsyncTask<String, Void, Product> { 

    public String url = "myexample.com" //yes, in my code it is a real url ;) 

    private Product getInformationForBarcode(String barcode) { 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(this.url); 

     try { 
      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("ean", barcode)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      if(response.getEntity().getContentLength() > 0){ 
       Product product = new Product(); 
       HttpEntity entity = response.getEntity(); 
       StringBuilder sb = new StringBuilder(); 
       try { 
        BufferedReader reader = 
          new BufferedReader(new InputStreamReader(entity.getContent()), 65728); 
        String line = null; 

        while ((line = reader.readLine()) != null) { 
         sb.append(line); 
        } 
        String[] productData = sb.toString().split(";"); 

        product.setName(productData[0]); 
        product.setProducer(productData[1]); 
       } 
       catch (IOException e) { e.printStackTrace(); } 
       catch (Exception e) { e.printStackTrace(); } 

       Log.e("finalResult " , sb.toString()); 
       product.setBarcode(barcode); 
       return product; 
      } 
     } 
     catch(Exception e) 
     { 
      Log.e("log_tag", "Error: " + e.toString()); 
     } 
     return null; 
    } 

    @Override 
    protected Product doInBackground(String... param) { 
     getInformationForBarcode(result); 
     return null; 
    } 
} 

我希望有人能幫助我與。

回答

0

此檢查

if(response.getEntity().getContentLength() > 0) 

是不正確的。 http標頭ContentLength可以設置爲0. rfc不強制指定正確的大小。您應該檢查http請求的響應代碼。檢查應該是:

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 

然後嘗試讀取響應的內容。通過rfc HTTP 200是request okHTTP 204Request ok No Content

+0

他不做if。我能得到的最後一行是執行。之後,他打破了嘗試。 09-28 10:53:51.824 16318-16601 /? E/log_tag:錯誤:javax.net.ssl.SSLPeerUnverifiedException:沒有對等證書 這就是我得到的。 – user3244807

+0

是https https嗎? – Blackbelt

+0

是的。刪除s? – user3244807