首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android HttpPost:如何获取结果

Android HttpPost:如何获取结果
EN

Stack Overflow用户
提问于 2010-02-24 12:12:32
回答 6查看 90.2K关注 0票数 50

我已经尝试了很长时间来发送HttpPost请求和检索响应,但是即使我能够建立连接,我仍然不知道如何获取由请求-响应返回的字符串消息

代码语言:javascript
复制
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php");
 // Add your data   
 List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > (5);
 nameValuePairs.add(new BasicNameValuePair("type", "20"));
 nameValuePairs.add(new BasicNameValuePair("mob", "919895865899"));
 nameValuePairs.add(new BasicNameValuePair("pack", "0"));
 nameValuePairs.add(new BasicNameValuePair("exchk", "1"));

 try {
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     Log.d("myapp", "works till here. 2");
     try {
         HttpResponse response = httpclient.execute(httppost);
         Log.d("myapp", "response " + response.getEntity());
     } catch (ClientProtocolException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }
 } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
 } 

对不起,我听起来很天真,因为我刚接触java。请帮帮我。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-02-24 17:01:49

尝试在您的响应上使用EntityUtil

代码语言:javascript
复制
String responseBody = EntityUtils.toString(response.getEntity());
票数 99
EN

Stack Overflow用户

发布于 2010-02-24 13:09:56

代码语言:javascript
复制
    URL url;
    url = new URL("http://www.url.com/app.php");
    URLConnection connection;
    connection = url.openConnection();
    HttpURLConnection httppost = (HttpURLConnection) connection;
    httppost.setDoInput(true);
    httppost.setDoOutput(true);
    httppost.setRequestMethod("POST");
    httppost.setRequestProperty("User-Agent", "Tranz-Version-t1.914");
    httppost.setRequestProperty("Accept_Language", "en-US");
    httppost.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
    DataOutputStream dos = new DataOutputStream(httppost.getOutputStream());
    dos.write(b); // bytes[] b of post data

    String reply;
    InputStream in = httppost.getInputStream();
    StringBuffer sb = new StringBuffer();
    try {
        int chr;
        while ((chr = in.read()) != -1) {
            sb.append((char) chr);
        }
        reply = sb.toString();
    } finally {
        in.close();
    }

这段代码行得通。经过长时间的搜索,我得到了它,但从一个J2ME代码。

票数 8
EN

Stack Overflow用户

发布于 2010-02-26 04:42:04

您可以使用ResponseHandler调用execute方法。下面是一个例子:

代码语言:javascript
复制
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httppost, responseHandler);
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2323617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档