2012-12-04 64 views
0

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

我接着就从复制并粘贴顶部教程:http://hc.apache.org/httpcomponents-client-ga/quickstart.html

我进口的一切,留下了这个错误:

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

的这部分程序是在教程中两个地方,并且在两者都发生错误。 Eclipse中说,对第一行:

"The method consume(HttpEntity) is undefined for the type EntityUtils."

下联:

"The method releaseConnection() is undefined for the type HttpGet."

我敢肯定,我下载的每一个罐子,正确运输它们,进口一切。什么是造成错误?谢谢。

这是我现在拥有的。爱德华,我使用了你方法中的一些代码,但只是把它们放到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; 
    } 
    } 
+0

在您选择仍然在使用来自Android的SDK库,因为它USIG相同的包名称...尝试http://code.google.com/p/httpclientandroidlib/或由于Android没有从Apache的使用文档已经事实有这个库,但早期版本 – Selvin

+0

为什么你用两种不同的方式设置两次params? – MrHIDEn

回答

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(); 

而且,你不应该甚至从你的UI线程中做网络I /从的onCreate()O,或者因为它可以阻止很长时间,冻结您的整个UI,并可能引起“应用未响应“(ANR)崩溃。但是对于一个简单的测试程序,你可以让它现在滑动。对于产品代码,您可以启动一个线程或使用AsyncTask()。

无论如何,我们并不是真的有兴趣为您构建和调试程序。你有没有试过这个代码?结果是什么?

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


原来的答复:

我认为您看到了挂住了。 Apache http客户端软件包内置于Android,因此不需要从apache下载任何jar文件。

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

releaseConnection()调用可能只是持久连接所必需的。这是相对高级的用法;我甚至没有在自己的代码中执行持久或受管理的连接。

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

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

的程序是:

  • 创建DefaultHttpClient
  • 创建HttpPost请求
    • 根据需要用setHeader()addHeader()添加报头。
    • 添加数据,以在HttpEntity
  • 呼叫client.execute()与柱请求
  • 等待的形式来发送和接收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; 
    } 
} 
+0

我更新了我目前的代码,请你看看它吗?谢谢! – onepiece