没有结果的Android httppost

时间:2015-09-28 08:34:24

标签: android

我试图将字符串发布到php脚本。这个脚本返回一个字符串,其中的值由分号分隔(例如" hello; world")。

我为这个字符串实现了一个测试,所以我可以在浏览器中测试它并且它可以工作。但我的应用程序没有得到任何结果。

这是我的代码

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

我希望有人可以帮助我。

1 个答案:

答案 0 :(得分: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