0

我正在尝试将文本从 Android 输入到网站中,并且我读到 httppost 是一个不错的选择。我下载了 HttpClient 4.2.2 (GA) tar.gz,解压缩它们,然后将 7 个 jars 复制到 Eclipse 中我的 android 项目的 lib 文件夹中。我很确定我得到了所有的罐子,因为它们与网站上列出的那些相匹配。

然后我继续从以下位置复制并粘贴顶级教程: http: //hc.apache.org/httpcomponents-client-ga/quickstart.html

我导入了所有内容,并留下了这个错误:

   EntityUtils.consume(entity1);  //X
    } finally {
       httpGet.releaseConnection();  //X

这部分代码位于教程中的两个地方,并且两个地方都会出现错误。Eclipse 说第一行:

“EntityUtils 类型的方法 consume(HttpEntity) 未定义。”

第二行:

“对于 HttpGet 类型,方法 releaseConnection() 未定义。”

我很确定我下载了每个 jar,正确传输它们,并导入了所有内容。是什么造成了错误?谢谢。

这就是我现在所拥有的。爱德华,我使用了您方法中的一些代码,但只是将它们放入 onCreate。但是,这是行不通的。从上一个活动转到此活动几秒钟后,我收到应用程序“已意外停止”的消息。

我有一个关于将字符串输入网站文本字段的问题:我是否使用 HttpParams 的 NameValuePairs?这是我的代码,你能看出有什么问题吗?谢谢。

    package com.example.myapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class BalanceCheckerActivity extends Activity {

private final String LOGIN_URL = "https://someloginsite.com"; //username and password

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_balance_checker);

        String username = getIntent().getExtras().getString("username");
        String password = getIntent().getExtras().getString("password");

        //Building post parameters, key and value pair
        List<NameValuePair> accountInfo = new ArrayList<NameValuePair>(2);
        accountInfo.add(new BasicNameValuePair("inputEnterpriseId", username));
        accountInfo.add(new BasicNameValuePair("password", password));

        //Creating HTTP client
        HttpClient httpClient = new DefaultHttpClient();

        //Creating HTTP Post
        HttpPost httpPost = new HttpPost(LOGIN_URL);

        BasicHttpParams params = new BasicHttpParams();
        params.setParameter("inputEnterpriseID", username);
        params.setParameter("password", password);
        httpPost.setParams(params);

        //Url Encoding the POST parameters
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(accountInfo));
        }
        catch (UnsupportedEncodingException e) {
            // writing error to Log
            e.printStackTrace();
            startActivity(new Intent(this, AccountInputActivity.class));
        }

        HttpResponse response = null;
        InputStreamReader iSR = null;
        String source = null;

     // Making HTTP Request
        try {
            response = httpClient.execute(httpPost);

            // writing response to log
            Log.d("Http Response:", response.toString());

            iSR = new InputStreamReader(response.getEntity().getContent());

            BufferedReader br = new BufferedReader(iSR);   
            source = "";

            while((source = br.readLine()) != null)
            {
                source += br.readLine();
            }

        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
            startActivity(new Intent(this, AccountInputActivity.class));

        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
            startActivity(new Intent(this, AccountInputActivity.class));
        }
        System.out.println(source);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_balance_checker, menu);
        return true;
    }
    }
4

1 回答 1

2

这对我来说看起来很不错。我只看到了一段明显错误的代码:

while((source = br.readLine()) != null)
{
    source += br.readLine();
}

这有点乱,与其试图解开它,我只会重写它。

StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
  sb.append(line);
String source = sb.toString();

此外,您不应该从 onCreate() 甚至在您的 UI 线程中执行网络 I/O,因为它可能会阻塞很长时间,冻结您的整个 UI 并可能导致“应用程序无响应”(ANR)崩溃. 但是对于一个简单的测试程序,你现在可以让它滑动。对于生产代码,您将启动一个线程或使用 AsyncTask()。

无论如何,我们对为您构建和调试程序并不真正感兴趣。你试过这个代码吗?结果如何?

最后一点:像这样的登录序列可能会以 cookie 的形式返回身份验证令牌。我忘记了您如何从 HttpResponse 中提取 cookie,但您会希望这样做,然后将任何收到的 cookie 作为对该网站的任何后续请求的一部分包含在内。


原答案:

我想你已经把自己搞得一团糟了。Android 内置了 Apache http 客户端包,因此无需从 apache 下载任何 jar 文件。

我不熟悉 EntityUtils,但不管它是什么,如果你可以避免使用它,我会这样做。尽可能坚持使用捆绑的 API;您添加到应用程序的每个第三方或实用程序库都会增加臃肿,在移动设备上,您希望让应用程序尽可能轻巧。至于consume()没有找到实际的“”方法,这可能是文档中的错误。他们大概的意思consumeContent()

releaseConnection()调用可能仅对持久连接是必需的。那是相对高级的用法;我什至不在自己的代码中进行持久连接或托管连接。

您没有提供足够的信息来让我们知道您正在尝试做什么,但我会尝试给您一个合理的通用答案。

通过 http 协议将数据传输到服务器的方法有很多很多,但在绝大多数情况下,您希望通过 HttpPost 传输表单编码的数据。

程序是:

  • 创建一个DefaultHttpClient
  • 创建HttpPost请求
    • setHeader()使用或根据需要添加标题addHeader()
    • 添加要传输的数据,格式为HttpEntity
  • client.execute()使用 post 请求调用
  • 等待并收到一个HttpResponse; 检查它的状态代码。
  • 如果您希望从服务器返回数据,请使用response.getEntity()

有许多HttpEntity类,它们收集它们的数据并以各自的方式将其传输到服务器。假设您正在传输表单编码的数据,那么UrlEncodedFormEntity就是您想要的数据。该实体获取一个NameValuePair对象列表,它为表单编码数据正确格式化并传输它。

这是我为此编写的一些代码;这些只是代码片段,所以我会留给您将它们合并到您的应用程序中并自己调试它们。

/**
 * POST the given url, providing the given list of NameValuePairs
 * @param url   destination url
 * @param data  data, as a list of name/value pairs
 */
public HttpResponse post(String url, List<NameValuePair> data) {
    HttpPost req = new HttpPost(url);
    UrlEncodedFormEntity e;
    try {
        e = new UrlEncodedFormEntity(data, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        Log.e(TAG, "Unknown exception: " + e1);
        return null;   // Or throw an exception, it's up to you
    }
    return post(req, e);
}

/**
 * Post an arbitrary entity.
 * @param req   HttpPost
 * @param data  Any HttpEntity subclass
 * @return HttpResponse from server
 */
public HttpResponse post(HttpPost req, HttpEntity data) {
    try {
        HttpClient client = new DefaultHttpClient();
        req.setEntity(data);
        HttpResponse resp = client.execute(req);
        int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            Log.w(TAG,
              "http error: " + resp.getStatusLine().getReasonPhrase());
            return null;   // Or throw an exception, it's up to you
        }
        return resp;
    } catch (ClientProtocolException e) {
        Log.e(TAG, "Protocol exception: " + e);
        return null;
    } catch (UnknownHostException e) {
        return null;
    } catch (IOException e) {
        Log.e(TAG, "IO exception: " + e);
        return null;
    } catch (Exception e) {
        // Catch-all
        Log.e(TAG, "Unknown exception: " + e);
        return null;
    }
}
于 2012-12-04T02:37:42.050 回答