如果您对Java-apachehttp客户端用法示例,显示cookie的使用以及从HTTPResponse对象提取响应感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Java-apachehtt
如果您对Java-apache http客户端用法示例,显示cookie的使用以及从HTTPResponse对象提取响应感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Java-apache http客户端用法示例,显示cookie的使用以及从HTTPResponse对象提取响应的各种细节,此外还有关于04_HttpResponse对象及使用其设置cookie详解、android – 从org.apache.http.HttpResponse获取建议的文件名、android.net.http.HttpResponseCache的实例源码、Apache HttpClient临时错误:NoHttpResponseException的实用技巧。
本文目录一览:- Java-apache http客户端用法示例,显示cookie的使用以及从HTTPResponse对象提取响应
- 04_HttpResponse对象及使用其设置cookie详解
- android – 从org.apache.http.HttpResponse获取建议的文件名
- android.net.http.HttpResponseCache的实例源码
- Apache HttpClient临时错误:NoHttpResponseException
Java-apache http客户端用法示例,显示cookie的使用以及从HTTPResponse对象提取响应
我正在使用Java Web应用程序中的apache http客户端(v4),并且在以下情况下遇到问题,对于这些情况,我需要简单的用法示例-
(1)如何将Cookie与Apache HTTP客户端一起使用,使用Cookie的可用选项不同
(2)当响应在HTTPResponse对象中可用时,提取字符集,模仿类型,响应头(作为KeyValuePair)和budy(作为byte [])。
答案1
小编典典1)AS为cookie,请参见示例:
httpcomponents-client-4.1.3 \ examples \ org \ apache \ http \ examples \
client \ ClientCustomContext.java
主要代码:
HttpClient httpclient = new DefaultHttpClient(); try { // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // Pass local context as a parameter HttpResponse response = httpclient.execute(httpget, localContext); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
2)您可以从响应中获得所需的一切,并且:
HttpEntity entity = response.getEntity();entity.getContent()
只需阅读以下示例:httpcomponents-client-4.1.3-bin.zip的httpcomponents-client-4.1.3 \
examples \ org \ apache \ http \ examples \
client(可从其网站下载)。
04_HttpResponse对象及使用其设置cookie详解
HttpResponse 对象
Django服务器接收到客户端发送过来的请求后,会将提交上来的这些数据封装成一 个 HttpRequest 对象传给视图函数。那么视图函数在处理完相关的逻辑后,也需要返回一个响应 给浏览器。而这个响应,我们必须返回 HttpResponseBase 或者他的子类的对象。 而 HttpResponse 则是 HttpResponseBase 用得最多的子类。那么接下来就来介绍一 下 HttpResponse 及其子类
1. 常用属性
-
content:返回的内容。
-
status_code:返回的HTTP响应状态码。
-
content_type:返回的数据的MIME类型,默认为 text/html 。浏览器会根据这个属性,来显 示数据。如果是 text/html ,那么就会解析这个字符串,如果 text/plain ,那么就会显示一 个纯文本。常用的 Content-Type 如下: text/html(默认的,html文件) text/plain(纯文本) text/css(css文件) text/javascript(js文件) multipart/form-data(文件提交) application/json(json传输) application/xml(xml文件)
-
设置请求头: response[''X-Access-Token''] = ''xxxx'' 。
2. 常用方法
-
init :使用页内容实例化HttpResponse对象
-
write(content):以文件的方式写
-
flush():以文件的方式输出缓存区
-
set_cookie(key, value='''', max_age=None, expires=None):设置Cookie key、value都是字符串类型 max_age是一个整数,表示在指定秒数后过期 expires是一个datetime或timedelta对象,会话将在这个指定的日期/时间过期,注意datetime和timedelta值只有在使用PickleSerializer时才可序列化 如果max_age 和expires 都没有指定,则是 表示关闭浏览器就失效
-
delete_cookie(key):删除指定的key的Cookie,如果key不存在则什么也不发生
注意: 注意:设置cookie值以及删除cookie值都是response对象的操作,而获取cookie是从request相应中获得的.
android – 从org.apache.http.HttpResponse获取建议的文件名
例如.在PHP中,你会这样做:
header('Content-disposition: attachment; filename=blah.txt');
如何使用Android / Java中的Apache类获取“blah.txt”?
解决方法
BasicHeader header = new BasicHeader("Content-disposition","attachment; filename=blah.txt"); HeaderElement[] helelms = header.getElements(); if (helelms.length > 0) { HeaderElement helem = helelms[0]; if (helem.getName().equalsIgnoreCase("attachment")) { NameValuePair nmv = helem.getParameterByName("filename"); if (nmv != null) { System.out.println(nmv.getValue()); } } }
SYSOUT> blah.txt
android.net.http.HttpResponseCache的实例源码
/** * Fetches an entry value from the Httpresponsecache cache * @param connection connection from which we need the cache * @param uri uri to use to get the cache entry * @return cache entry value as String */ private String fetchFromHTTPUrlConnectionCache(HttpURLConnection connection,URI uri) { try { Httpresponsecache responsecache = Httpresponsecache.getInstalled(); if(responsecache != null){ CacheResponse cacheResponse = responsecache.get(uri,"GET",connection.getRequestProperties()); Scanner scanner = new Scanner(cacheResponse.getBody(),"UTF-8"); StringBuilder sb = new StringBuilder(); while (scanner.hasNextLine()){ sb.append(scanner.nextLine()); } return sb.toString(); } } catch (Exception ex) { ex.printstacktrace(); } return null; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_pane); Toolbar toolbar = (Toolbar) findViewById(R.id.app_toolbar); setSupportActionBar(toolbar); if (savedInstanceState == null) { FragmentManager.enableDebugLogging(true); getSupportFragmentManager().beginTransaction() .add(R.id.container,SampleListFragment.newInstance(),SampleListFragment.TAG) .commit(); } // http response cache File httpCacheDir = new File(getCacheDir(),"http"); long httpCacheSize = 100 * 1024 * 1024; // 100 MiB try { Httpresponsecache.install(httpCacheDir,httpCacheSize); } catch (IOException e) { Log.i(SampleListActivity.class.getSimpleName(),"HTTP response cache installation Failed:" + e); } }
@Override public void onCreate() { super.onCreate(); // cookie store CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cookieManager); // init cache for http responses try { File httpCacheDir = new File(getApplicationContext().getCacheDir(),"http"); long httpCacheSize = 10 * 1024 * 1024; // 10 MiB Httpresponsecache.install(httpCacheDir,httpCacheSize); } catch(IOException e){ Log.i(TAG,"HTTP response cache installation Failed:" + e); } }
public static RestAdapter.Builder getRestBuilder(final Context context,final String url) { if (!sresponsecache) { try { final File httpCacheDir = new File(context.getCacheDir(),"http"); final long httpCacheSize = 10 * 1024 * 1024; // 10 MiB Httpresponsecache.install(httpCacheDir,httpCacheSize); } catch (IOException e) { e.printstacktrace(); } sresponsecache = true; } return new RestAdapter.Builder() .setEndpoint(url) .setConverter(JACKSON_CONVERTER) .setRequestInterceptor(new RequestInterceptor() { @Override public void intercept(RequestFacade request) { request.addHeader("Authorization","Basic " + XDAConstants.ENCODED_AUTHORIZATION); } }); }
protected void onStop() { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
@Override protected void onStop() { super.onStop(); Httpresponsecache cache = Httpresponsecache.getInstalled(); if(cache != null) { //Clearing the cache cache.flush(); } }
public void cacher() { httpCacheDir = getExternalCacheDir(); try { Httpresponsecache.install(httpCacheDir,httpCacheSize); //Setting the cache } catch (Exception e) { e.printstacktrace(); } }
@Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { Httpresponsecache.install(new File(getCacheDir(),"http"),5 * 1024 * 1024); } catch (IOException e) { Log.e(getClass().getSimpleName(),"Could not register cache " + e.getMessage()); } } PreferenceManager.setDefaultValues(this,R.xml.settings,false); Thread.setDefaultUncaughtExceptionHandler(new YalpStoreUncaughtExceptionHandler(getApplicationContext())); registerDownloadReceiver(); registerinstallreceiver(); }
/** * Enable caching for http request : must use HttpUrlConnection ! * see : <a href="http://developer.android.com/reference/android/net/http/Httpresponsecache.html">Httpresponsecache</a> * * @param context */ public static void enableHttpCaching(Context context) { long httpCacheSize = 10 * 1024 * 1024; // 10 MiB try { File httpCacheDir = new File(context.getCacheDir(),"http"); Httpresponsecache.install(httpCacheDir,httpCacheSize); } catch (IOException e) { Log.i("","HTTP response cache Failed:" + e); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { File httpCacheDir = new File(getCacheDir(),"http"); long httpCacheSize = 0; Httpresponsecache.install(httpCacheDir,httpCacheSize); } catch (IOException e) { Log.i(getClass().getName(),"HTTP response cache installation Failed:" + e); } }
protected void onStop() { super.onStop(); Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
@Override public void put(Request key,HttpResponse value) { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
@Override public void clear() throws IOException { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.delete(); } Httpresponsecache.install(file,size); }
@Override protected void onStop() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { final Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } } super.onStop(); }
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void enableHttpresponsecache() { final long httpCacheSize = 10 * 1024 * 1024; final File httpCacheDir = new File(getCacheDir(),"http"); try { Httpresponsecache.install(httpCacheDir,httpCacheSize); } catch (final IOException e) { throw new RuntimeException(e); } }
@Override protected void onPause() { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } super.onPause(); }
/** * Installs the Httpresponsecache * Note this will only work on Android 4.0+ */ private void enableHttpresponsecache() { try { long httpCacheSize = 10 * 1024 * 1024; // 10 MiB File httpCacheDir = new File(getCacheDir(),httpCacheSize); } catch (Exception httpresponsecacheNotAvailable) { Log.d(TAG,"HTTP response cache is unavailable."); } }
/** * Invalidates both Httpresponsecache and Volley cache * @param view */ public void invalidateCache(View view) { mRequestQueue.getCache().clear(); try { Httpresponsecache cache = Httpresponsecache.getInstalled(); if(cache != null) cache.delete(); } catch (IOException e) { e.printstacktrace(); } Toast.makeText(this,"Cache is Now empty",Toast.LENGTH_SHORT).show(); }
@Override protected void onStop() { super.onStop(); Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
private static void enableHttpresponsecache(Context context) { try { long httpCacheSize = 5 * 1024 * 1024; // 5MB File httpCacheDir = new File(context.getCacheDir(),httpCacheSize); } catch (IOException e) { AppLog.w(T.UTILS,"Failed to enable http response cache"); } }
protected void onStop() { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } super.onStop(); }
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private static Httpresponsecache installHttpresponsecache(final File cacheDir) throws IOException { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache == null) { final long maxSize = calculatediskCacheSize(cacheDir); cache = Httpresponsecache.install(cacheDir,maxSize); } return cache; }
static Object install(Context context) throws IOException { File cacheDir = Utils.createDefaultCacheDir(context); Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache == null) { long maxSize = Utils.calculatediskCacheSize(cacheDir); cache = Httpresponsecache.install(cacheDir,maxSize); } return cache; }
@Implementation public static Httpresponsecache install(File directory,long maxSize) { Httpresponsecache cache = newInstanceOf(Httpresponsecache.class); ShadowHttpresponsecache shadowCache = Robolectric.shadowOf(cache); shadowCache.originalObject = cache; shadowCache.directory = directory; shadowCache.maxSize = maxSize; synchronized (LOCK) { installed = shadowCache; return cache; } }
@Test public void installedCacheIsReturned() throws Exception { assertthat(Httpresponsecache.getInstalled()).isNull(); Httpresponsecache cache = Httpresponsecache.install(File.createTempFile("foo","bar"),42); Httpresponsecache installed = Httpresponsecache.getInstalled(); assertthat(installed).isSameAs(cache); assertthat(installed.maxSize()).isEqualTo(42); }
@Test public void countsstartAtZero() throws Exception { Httpresponsecache cache = Httpresponsecache.install(File.createTempFile("foo",42); assertthat(cache.getHitCount()).isZero(); assertthat(cache.getNetworkCount()).isZero(); assertthat(cache.getRequestCount()).isZero(); }
private Api(Context context) { try { File httpCacheDir = new File(context.getCacheDir(),httpCacheSize); } catch (IOException e) { Log.i("Api","HTTP response cache installation Failed:" + e); } }
@Override public void close() throws IOException { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
static Object install(Context context) throws IOException { File cacheDir = Utils.createDefaultCacheDir(context); Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache == null) { long maxSize = Utils.calculatediskCacheSize(cacheDir); cache = Httpresponsecache.install(cacheDir,maxSize); } return cache; }
@Override public void onStop() { super.onStop(); mAdapter.changeCursor(null); Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
/** * */ private void initCacheFile() { try { httpCacheDir = new File(getCacheDir(),"http"); httpCacheDir.setReadable(true); Httpresponsecache.install(httpCacheDir,httpCacheSize); cache = new Cache(httpCacheDir,httpCacheSize); } catch (Exception e) { e.printstacktrace(); } }
@Override public void onTerminate() { super.onTerminate(); // Todo clear cookiestore content here // remove cached files Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
@Override public void run() { Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND); final Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) cache.flush(); }
public DefaultDownloader(Context context) { cacheDir = new File(context.getCacheDir(),"http"); try { Httpresponsecache.install(cacheDir,cacheSize); } catch (IOException e) { Log.i(TAG,"HTTP response cache installation Failed:" + e); } }
@Override public void onCreate() { super.onCreate(); File httpCacheDir = new File(getCacheDir(),HTTP_CACHE_SIZE); } catch (IOException e) { Log.e(TAG,"Failed to create http cache!",e); } }
private void tryInstallresponsecache() { if(Httpresponsecache.getInstalled() == null) { File cacheDir = new File(getCacheDir(),"http"); try { Httpresponsecache.install(cacheDir,10 * 1024 * 1024); } catch (IOException e) { Log.w(TAG,"Creating response cache",e); } } }
@AfterInject @Trace(tag = TAG,level = Log.DEBUG) void init() { // if (BuildConfig.DEBUG) { // aviewPrefs.pref_openedDrawer().put(false); // } // Create a unique id for this install if one doesn't already exist if (!aviewPrefs.ivid().exists()) { if (Log.isLoggable(TAG,Log.DEBUG)) Log.d(TAG,"Creating new ivid"); aviewPrefs.ivid().put(UUID.randomUUID().toString()); } if (Log.isLoggable(TAG,Log.DEBUG)) Log.d(TAG,"ivid=" + aviewPrefs.ivid().get()); // Create a cache for automatically caching HTTP requests try { File httpCacheDir = new File(this.getCacheDir(),httpCacheSize); } catch (IOException e) { if (Log.isLoggable(TAG,Log.INFO)) Log.i(TAG,"HTTP response cache installation Failed:" + e); } }
@Override @Trace public void onTerminate() { super.onTerminate(); aviewVideoService.close(); Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } }
@Override protected void onStop() { Httpresponsecache cache = Httpresponsecache.getInstalled(); if (cache != null) { cache.flush(); } eventBus.unregister(this); super.onStop(); }
public FileCache(File file,long size) throws IOException { this.file = file; this.size = size; Httpresponsecache.install(file,size); }
Apache HttpClient临时错误:NoHttpResponseException
我有一个Web服务正在接受XML的POST方法。它工作正常,然后在某个随机的时刻,它无法与服务器通信,并抛出message,并抛出IOExceptionThe target server failed to respond
。后续调用工作正常。
当我打了一些电话然后将应用程序闲置大约10-15分钟时,它就会发生。在此之后我进行的第一个调用将返回此错误。
我尝试了几件事…
我像这样设置重试处理程序
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException e, int retryCount, HttpContext httpCtx) { if (retryCount >= 3){ Logger.warn(CALLER, "Maximum tries reached, exception would be thrown to outer block"); return false; } if (e instanceof org.apache.http.NoHttpResponseException){ Logger.warn(CALLER, "No response from server on "+retryCount+" call"); return true; } return false; } }; httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
但是此重试从未被调用过。(是的,我正在使用正确的instanceof子句)。在调试时,此类永远不会被调用。
我什至尝试设置HttpProtocolParams.setUseExpectContinue(httpClient.getParams(),false);
但没有用。有人可以建议我现在可以做什么吗?
重要事项 除了弄清楚为什么我会得到例外,我还有一个重要的担忧是为什么重试处理程序不在这里工作?
答案1
小编典典由连接管理器保持活动状态的最有可能的持久连接变得陈旧。也就是说,目标服务器会在其连接空闲时关闭其末端的连接,而HttpClient无法对该事件做出反应,从而使连接半关闭或“陈旧”。通常这不是问题。HttpClient使用多种技术来验证从池中租借时的连接有效性。即使禁用了过时的连接检查并且使用了过时的连接来传输请求消息,请求执行通常也会在具有SocketException的写操作中失败,并会自动重试。但是,在某些情况下,写操作可以毫无例外地终止,随后的读操作将返回-1(流的结尾)。
解决此问题的最简单方法是将过期的连接和闲置了超过一段时间(例如,在池中闲置一分钟之后)之后空闲的连接驱逐出去。有关详细信息,请参见HttpClient教程的本节。
我们今天的关于Java-apache http客户端用法示例,显示cookie的使用以及从HTTPResponse对象提取响应的分享已经告一段落,感谢您的关注,如果您想了解更多关于04_HttpResponse对象及使用其设置cookie详解、android – 从org.apache.http.HttpResponse获取建议的文件名、android.net.http.HttpResponseCache的实例源码、Apache HttpClient临时错误:NoHttpResponseException的相关信息,请在本站查询。
本文标签: