关键词:
【中文标题】Android 项目使用 httpclient --> http.client (apache), post/get 方法【英文标题】:Android project using httpclient --> http.client (apache), post/get method 【发布时间】:2009-05-17 09:22:17 【问题描述】:我正在为一个 android 项目执行 Get 和 Post 方法,我需要将 HttpClient 3.x“翻译”为 HttpClient 4.x(由 android 使用)。 我的问题是我不确定我做了什么,我没有找到一些方法的“翻译”......
这是我已经完成的 HttpClient 3.x 和 (-->) HttpClient 4.x “翻译”(如果我找到的话)(仅限向我提出问题的各方):
HttpState state = new HttpState (); --> ?
HttpMethod method = null; --> HttpUriRequest httpUri = null;
method.abort(); --> httpUri.abort(); //httpUri is a HttpUriRequest
method.releaseConnection(); --> conn.disconnect(); //conn is a HttpURLConnection
state.clearCookies(); --> cookieStore.clear(); //cookieStore is a BasicCookieStore
HttpClient client = new HttpClient(); --> DefaultHttpClient client = new DefaultHttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT) --> HttpConnectionParams.setConnectionTimeout(param, SOCKET_TIMEOUT);
client.setState(state); --> ?
client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); --> HttpClientParams.setCookiePolicy(param, CookiePolicy.RFC_2109);
PostMethod post = (PostMethod) method; --> ?
post.setRequestHeader(...,...); --> conn.setRequestProperty(...,...);
post.setFollowRedirects(false); --> conn.setFollowRedirects(false);
RequestEntity tmp = null; --> ?
tmp = new StringRequestEntity(...,...,...); --> ?
int statusCode = client.executeMethod(post); --> ?
String ret = method.getResponsBodyAsString(); --> ?
Header locationHeader = method.getResponseHeader(...); --> ?
ret = getPage(...,...); --> ?
我不知道这是否正确。 这引起了问题,因为包的名称不同,一些方法也不同。 我只需要文档(我还没有找到)和很少的帮助。
【问题讨论】:
【参考方案1】:这里是HttpClient 4 docs,这是 Android 正在使用的(4,而不是 3,截至 1.0->2.x)。文档很难找到(感谢 Apache ;)),因为 HttpClient 现在是 HttpComponents 的一部分(如果你只是寻找 HttpClient,你通常会在 3.x 的东西上结束)。
此外,如果您执行任意数量的请求,您不希望一遍又一遍地创建客户端。相反,作为tutorials for HttpClient note,创建一次客户端并保留它。从那里使用ThreadSafeConnectionManager。
我使用了一个辅助类,例如 HttpHelper 之类的东西(它仍然是一个移动的目标 - 我计划在某个时候将它移动到它自己的 Android util 项目中,并支持二进制数据,还没有到达那里),以帮助解决此问题。助手类创建客户端,并为 get/post/etc 提供方便的包装方法。在任何从Activity 使用此类的地方,您都应该创建一个内部内部AsyncTask(这样您在发出请求时就不会阻塞 UI 线程),例如:
private class GetBookDataTask extends AsyncTask<String, Void, Void>
private ProgressDialog dialog = new ProgressDialog(BookScanResult.this);
private String response;
private HttpHelper httpHelper = new HttpHelper();
// can use UI thread here
protected void onPreExecute()
dialog.setMessage("Retrieving HTTP data..");
dialog.show();
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(String... urls)
response = httpHelper.performGet(urls[0]);
// use the response here if need be, parse XML or JSON, etc
return null;
// can use UI thread here
protected void onPostExecute(Void unused)
dialog.dismiss();
if (response != null)
// use the response back on the UI thread here
outputTextView.setText(response);
【讨论】:
甚至比我的 HttpHelper 更好的是 ZXing 项目使用的那个 - code.google.com/p/zxing/source/browse/trunk/android/src/com/…。使用起来有点困难(尽管仍然很容易),而且能力更强。 (而且我在使用我写了很长时间的那个之后注意到它,类似的方法,虽然不完全相同,但收敛,而不是复制。;)。) HTTP 客户端文档已移动 — 现在位于:hc.apache.org/httpcomponents-client-ga/index.html 请记住,我的答案在这里是一个相当老的答案,而且我有一段时间没有更新那个帮助项目(我打算这样做,只是还没得到它)。从 API 级别 8 开始,Android 有自己的助手:developer.android.com/reference/android/net/http/… 另请注意,Android 团队的建议已更改。他们现在推荐标准的 java.net 东西而不是 HttpClient。有关 HttpURLConnection 的良好包装库,请参见:github.com/kevinsawicki/http-request【参考方案2】:回答我的问题的最简单方法是向您展示我制作的课程:
public class HTTPHelp
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private boolean abort;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
public HTTPHelp()
public void clearCookies()
httpClient.getCookieStore().clear();
public void abort()
try
if(httpClient!=null)
System.out.println("Abort.");
httpPost.abort();
abort = true;
catch (Exception e)
System.out.println("HTTPHelp : Abort Exception : "+e);
public String postPage(String url, String data, boolean returnAddr)
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try
tmp = new StringEntity(data,"UTF-8");
catch (UnsupportedEncodingException e)
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
httpPost.setEntity(tmp);
try
response = httpClient.execute(httpPost,localContext);
catch (ClientProtocolException e)
System.out.println("HTTPHelp : ClientProtocolException : "+e);
catch (IOException e)
System.out.println("HTTPHelp : IOException : "+e);
ret = response.getStatusLine().toString();
return ret;
我用this tutorial做我的post方法和thoses examples
【讨论】:
第二个链接移到hc.apache.org/httpcomponents-client-ga/examples.html 第一个链接移到hc.apache.org/httpcomponents-client-ga/tutorial/html【参考方案3】:嗯,你可以找到关于 HTTPClient
here 的那个版本的文档;浏览他们提供的example scenarios 特别有用。
不幸的是,我不知道 HTTPClient
的第 3 版,所以我不能给出直接的等价物;我建议您采取您正在尝试做的事情并查看他们的示例场景。
【讨论】:
谢谢,我会看一下文档,希望能找到我的问题的解决方案。【参考方案4】: package com.service.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/GetSubscriptionReportNames";//"http://tempuri.org/FahrenheitToCelsius";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME1 = "GetSubscriptionReportNames";//"FahrenheitToCelsius";
private static String URL = "http://icontrolusa.com:8040/iPhoneService.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
ArrayList<String> headlist = new ArrayList<String>();
ArrayList<String> reportlist = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
//Get the first property and change the label text
txtCel.setText(result.getProperty(0).toString());
Log.e("err ","output is :::: "+result.getProperty(0).toString());
parseSON();
else
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
catch (Exception e)
e.printStackTrace();
);
btnClear.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
txtCel.setText("");
txtFar.setText("");
);
private void parseSON()
headlist.clear();
reportlist.clear();
String text = txtCel.getText().toString() ;//sb.toString();
Log.i("######", "###### "+text);
try
JSONObject jobj = new JSONObject(text);
JSONArray jarr = jobj.getJSONArray("Head");
for(int i=0;i<jarr.length();i++)
JSONObject e = jarr.getJSONObject(i);
JSONArray names = e.names();
for(int j=0;j<names.length();j++)
String tagname = names.getString(j);
if (tagname.equals("ReportID"))
headlist.add(e.getString("ReportID"));
if (tagname.equals("ReportName"))
reportlist.add(e.getString("ReportName"));
catch(JSONException e)
Log.e("retail_home", "Error parsing data "+e.toString());
Log.d("length ", "head lenght "+headlist.size());
Log.d("value is ", "frst "+headlist.get(0));
Log.d("length ", "name lenght "+reportlist.size());
Log.d("value is ", "secnd "+reportlist.get(0));
【讨论】:
...但感谢您花时间发布您的代码!使用 HttpClient 4 通过 WiFi 进行 HTTPS 身份验证
】使用HttpClient4通过WiFi进行HTTPS身份验证【英文标题】:HTTPSauthenticationoverWiFiusingHttpClient4【发布时间】:2009-07-0923:17:10【问题描述】:我有Android宠物项目DroidIn,它利用HttpClient4(内置于Android)进行一些基于表单的身份验证。我... 查看详情
HttpClient 不可用共享库项目 Xamarin
】HttpClient不可用共享库项目Xamarin【英文标题】:HttpClientnotavailableSharedLibraryprojectXamarin【发布时间】:2016-03-2721:44:15【问题描述】:我来找您解决一个常见问题,但很遗憾,我无法找到解决方案。我制作了一个xamarin.form应用程序... 查看详情
使用 HttpClient 在 Android 中重用 SSL 会话
】使用HttpClient在Android中重用SSL会话【英文标题】:ReusingSSLSessionsinAndroidwithHttpClient【发布时间】:2011-08-0408:41:38【问题描述】:我在使用HttpClient在Android上恢复SSL会话时遇到了很多困难。我每90秒轮询一次服务器(它仅适用于具... 查看详情
使用 System.Net.HttpClient 进行上传时如何跟踪进度? [复制]
】使用System.Net.HttpClient进行上传时如何跟踪进度?[复制]【英文标题】:HowtotrackprogresswhenusingSystem.Net.HttpClientforupload?[duplicate]【发布时间】:2014-01-1512:52:37【问题描述】:我正在使用System.Net.HttpClient在我的iOS、Android和WP8项目中通... 查看详情
httpclient的post请求数据
...JDK自带的URLConnection。在项目组人员的推荐下,开始使用HttpClient。HttpClient简介:HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建... 查看详情
好程序员java教程分享使用httpclient抓取页面内容
好程序员Java教程分享使用HttpClient抓取页面内容,使用HttpClient工具来发送Http请求1.简介HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版... 查看详情
通用 Windows 项目 - HttpClient 异常
】通用Windows项目-HttpClient异常【英文标题】:UniversalWindowsproject-HttpClientexception【发布时间】:2016-01-1900:32:56【问题描述】:我正在尝试使用HttpClient在通用Windows项目(在Windows10通用应用程序中)中实现REST客户端,但以下行:varre... 查看详情
httpwebrequest改为httpclient踩坑记-请求头设置(代码片段)
原文:HttpWebRequest改为HttpClient踩坑记-请求头设置HttpWebRequest改为HttpClient踩坑记-请求头设置Intro这两天改了一个项目,原来的项目是.netframework项目,里面处理HTTP请求使用的是WebReauest,但是WebRequest已经不再推荐使用了,你如果在项... 查看详情
使用 Wifi 的 Android 上的 HttpClient 会导致延迟(在初始请求时)
】使用Wifi的Android上的HttpClient会导致延迟(在初始请求时)【英文标题】:HttpClientonAndroidusingWificausesdelay(oninitialrequest)【发布时间】:2011-04-2618:29:07【问题描述】:我在Android上遇到了HttpClient这个奇怪的问题。如果我尝试使用WiFi... 查看详情
Android HttpClient 和 Cookie
】AndroidHttpClient和Cookie【英文标题】:AndroidHttpClientandCookies【发布时间】:2012-12-1219:26:17【问题描述】:Android中的HttpClient存在问题:通过使用以下代码,我想通过webview登录来使用之前已经设置的cookie。所以登录数据应该在那里... 查看详情
Android API 23 - HttpClient 4.X 重新打包
】AndroidAPI23-HttpClient4.X重新打包【英文标题】:AndroidAPI23-HttpClient4.Xrepackaged【发布时间】:2015-08-2409:31:05【问题描述】:免责声明我知道我们不应该再在Android上使用HttpClient在API23中,我们可以选择使用useLibrary\'org.apache.http.legacy\'... 查看详情
Android - 如何使用 HttpClient 接受任何证书并同时传递证书
】Android-如何使用HttpClient接受任何证书并同时传递证书【英文标题】:Android-HowtoacceptanycertificatesusingHttpClientandpassingacertificateatthesametime【发布时间】:2011-09-2718:53:24【问题描述】:我有一个场景,我必须将证书传递给我的服务器... 查看详情
使用 Android HttpClient 重用 SSL 连接
】使用AndroidHttpClient重用SSL连接【英文标题】:SSLconnectionreusewithAndroidHttpClient【发布时间】:2012-09-2112:24:32【问题描述】:我正在我自己实现的javaweb代理(将请求转发到实际的web服务)和一个android应用程序之间开发一个安全的we... 查看详情
优雅编码之——传统项目中,使用openfeign替换掉项目中的httpclient(代码片段)
使用springcloud时,当遇到服务与其他服务调用的场景,一般都会使用springcloudopenfeign来进行调用。通过@feign注解让代码变得非常简单而又优雅,即便是跨服务的调用,写起来就像项目内部自己调自己的方法一样... 查看详情
优雅编码之——传统项目中,使用openfeign替换掉项目中的httpclient(代码片段)
使用springcloud时,当遇到服务与其他服务调用的场景,一般都会使用springcloudopenfeign来进行调用。通过@feign注解让代码变得非常简单而又优雅,即便是跨服务的调用,写起来就像项目内部自己调自己的方法一样... 查看详情
android6.0sdk中删除httpclient的相关类的解决方法
android6.0SDK中删除HttpClient的相关类的解决方法一、出现的情况在eclipse或androidstudio开发,设置androidSDK的编译版本为23时,且使用了httpClient相关类的库项目:如android-async-http等等,会出现有一些类找不到的错误。二... 查看详情
httpclient介绍和简单使用流程(代码片段)
1.HttpClientSpringCloud中服务和服务之间的调用全部是使用HttpClient,还有前面使用SolrJ中就封装了HttpClient,在调用SolrTemplate的saveBean方法时就调用HttpClient技术。当前大部分项目暴漏出来的接口是Http请求,数据格式是JSON格... 查看详情
如何在 Android 中使用 HTTPClient 以 JSON 格式发送 POST 请求?
】如何在Android中使用HTTPClient以JSON格式发送POST请求?【英文标题】:HowtosendPOSTrequestinJSONusingHTTPClientinAndroid?【发布时间】:2011-09-0706:28:57【问题描述】:我试图弄清楚如何使用HTTPClient从AndroidPOSTJSON。我一直试图弄清楚这一点,... 查看详情