2015-09-28 70 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