在android中没有获得http post请求的响应体?

时间:2011-02-09 13:13:51

标签: android

没有在android中获取http post请求的响应主体 我提到了名称值对中的用户ID,密码,并通过

输入了httppost请求
postrequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

但是在执行时我得到的响应为SC_OK(200),但响应正文为null

另一个问题是,如果我使用setHeader()函数在HTTPGet或HTTPPost的请求中指定标头,我将获得BAD REQUEST(404)响应。

请帮我解决上述问题。

谢谢&问候,
SSuman185

2 个答案:

答案 0 :(得分:1)

这是一种方便POST到页面并将响应作为字符串获取的方法。第一个参数(HashMap)是您要发送的参数的键值列表。没有错误处理,所以你必须这样做:

public static String doPost(HashMap<String,String> params, String url) {
        HttpPost httpost = new HttpPost(url);
        try {
            httpost.setURI(new URI(url));
        } catch (URISyntaxException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        HttpResponse response = null;

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();

        Set entryset = params.entrySet();
        Iterator iterator = entryset.iterator();
        Log.d("Posted URL: ", url+" ");
        while(iterator.hasNext()) {
            Map.Entry mapentry = (Map.Entry)iterator.next();
            String key = ((String)mapentry.getKey()).toString();
            String value = (String)mapentry.getValue();
            nvps.add(new BasicNameValuePair(key, value));

            Log.d("Posted param: ", key+" = "+value);
        }

        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            try {
                httpost.setURI(new URI(url));
            } catch (URISyntaxException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            response = getClient().execute(httpost);
            HttpEntity entity = response.getEntity();

            return convertStreamToString(entity.getContent());
        } catch (Exception e) {
            // some connection error occurred, nothing we can do
            e.printStackTrace();
        }

        return null;
    }

答案 1 :(得分:0)

嗨朋友请尝试这种方式从服务器获取响应..

其中,给定链接是您想要发布请求的链接..

String link2 = "http://184.106.227.45/quaddeals/university-of-illinois/androids_deals/user_card_list.json";

DefaultHttpClient hc1 = new DefaultHttpClient();

ResponseHandler<String> res1 = new BasicResponseHandler();

HttpPost postMethod1 = new HttpPost(link2);

List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1);

nameValuePairs1.add(new BasicNameValuePair("user_id",account_userId));

postMethod1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));

String response1 = hc1.execute(postMethod1, res1);