android与Web服务器交互时的cookie使用实例

 更新时间:2016年9月20日 20:01  点击:2215
本文章分享一篇关于android与Web服务器交互时的cookie使用实例有需要的同学可以参考一下。

下面是具体的代码
/**

* 向网站发送get请求,url需按照api要求写,返回取得的信息。

* //这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

* @param url

* @param client

* @return String

* @author lvqiyong

*/

 代码如下 复制代码

public static String getRequest1(String url, DefaultHttpClient client,

String charset) throws Exception {

String result = null;

int statusCode = 0;

HttpGet getMethod = new HttpGet(url);

Log.d(TAG, "do the getRequest,url=" + url + "");

try {

getMethod.setHeader("User-Agent", USER_AGENT);

getMethod.setHeader("Cookie", "cy=" + value);//这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

// 添加用户密码验证信息

// client.getCredentialsProvider().setCredentials(

// new AuthScope(null, -1),

// new UsernamePasswordCredentials(mUsername, mPassword));

 

HttpResponse httpResponse = client.execute(getMethod);

// statusCode == 200 正常

statusCode = httpResponse.getStatusLine().getStatusCode();

Log.d(TAG, "statuscode = " + statusCode);

// 处理返回的httpResponse信息

if (statusCode == 200) {

result = retrieveInputStream(httpResponse.getEntity(), charset);

Cookie cookie;

String cookname,cookvalue;

List<Cookie> cookies = client.getCookieStore().getCookies();

if (cookies.isEmpty()) {

Log.i(TAG, "-------Cookie NONE---------");

} else {

for (int i = 0; i < cookies.size(); i++) {

// 保存cookie

cookie = cookies.get(i);

cookname = cookie.getName().trim();

cookvalue = cookie.getValue().trim();

if(cookname.equals("cy")){

name = cookname;

value = cookvalue;

}

}

}

} else

result = "networkerror";

} catch (ConnectTimeoutException e) {// 超时或网络连接出错

result = "timeouterror";

// e.printStackTrace();

} catch (ClientProtocolException e) {

result = "networkerror";

// e.printStackTrace();

} catch (Exception e) {

result = "readerror";

Log.e(TAG, e.getMessage());

throw new Exception(e);

} finally {

getMethod.abort();

}

return result;

}

发一个异步图片加载控件。网上也有大把的异步网络加载图片的控件,但是有一个问题,异步加载会造成列表中的图片混乱,因为列表的每一项的View都可能被重用,异步加载的时候多个异步线程引用到了同一个View将造成图片加载错乱。该控件解决这个问题
 代码如下 复制代码

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 异步图片控件
 * 使用:new AsyncImageView().asyncLoadBitmapFromUrl("http://xxxx","缓存路径"){
 *
 * @author gaoomei@gmail.com
 * @site http://obatu.sinaapp.com
 * @version 1.0
 * @2011-12-3
 */
public class AsyncImageView extends ImageView {

 /**
  * 异步task加载器
  */
 private AsyncLoadImage mAsyncLoad;

 /**
  * 下载回来的图片缓存存活时间,单位:秒(s),默认30分钟
  */
 private long mCacheLiveTime = 1800;

 public AsyncImageView(Context context) {
  super(context);
 }

 public AsyncImageView(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 public AsyncImageView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
 }

 /**
  *
  */
 @Override
 public void setImageDrawable(Drawable drawable) {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
   mAsyncLoad = null;
  }
  super.setImageDrawable(drawable);
 }

 /**
  * 重写下面几个设置图片资源的方法,目地是取消网络加载
  */
 @Override
 public void setImageResource(int resId) {
  cancelLoad();
  super.setImageResource(resId);
 }

 @Override
 public void setImageURI(Uri uri) {
  cancelLoad();
  super.setImageURI(uri);
 }

 @Override
 public void setImageBitmap(Bitmap bitmap) {
  cancelLoad();
  super.setImageBitmap(bitmap);
 }

 /**
  * 取消正在进行的异步task
  */
 public void cancelLoad() {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
   mAsyncLoad = null;
  }
 }

 /**
  * 设置图片存活时间
  *
  * @param second
  *            存活时间,单位【秒】,如果等于0或null,则不缓存
  */
 public void setCacheLiveTime(long second) {
  if (second == 0) {
   this.mCacheLiveTime = 0;
  } else if (second >= 0) {
   this.mCacheLiveTime = second * 1000;
  }
 }

 /**
  * 从网络异步加载
  *
  * @param url
  * @param saveFileName
  */
 public void asyncLoadBitmapFromUrl(String url, String saveFileName) {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
  }
  // AsyncTask不可重用,所以每次重新实例
  mAsyncLoad = new AsyncLoadImage();
  mAsyncLoad.execute(url, saveFileName);
 }

 /**
  * 异步加载器
  */
 private class AsyncLoadImage extends AsyncTask {
  /**
   * 是否取消
   */
  private boolean isCancel = false;

  @Override
  protected Bitmap doInBackground(String... params) {
   if (isCancel) {
    return null;
   }
   String url = params[0];
   String fileName = params[1];
   try {
    return getBitmap(url, fileName);
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  @Override
  protected void onCancelled() {
   System.out.println("async load imgae cancel");
   isCancel = true;
  }

  @Override
  protected void onPostExecute(Bitmap result) {
   if (!isCancel && result != null) {
    AsyncImageView.this.setImageBitmap(result);
   }
  }
 }

 /**
  * 下载图片
  *
  * @param urlString
  *            url下载地址
  * @param fileName
  *            缓存文件路径
  * @throws IOException
  */
 private Bitmap getBitmap(String urlString, String fileName)
   throws IOException {
  if (fileName == null || fileName.trim().isEmpty()) {
   InputStream input = getBitmapInputStreamFromUrl(urlString);
   return BitmapFactory.decodeStream(input);
  }

  File file = new File(fileName);
  if (!file.isFile()
    || (mCacheLiveTime > 0 && (System.currentTimeMillis()
      - file.lastModified() > mCacheLiveTime))) {
   InputStream input = getBitmapInputStreamFromUrl(urlString);
   file = saveImage(input, fileName);
   // 如果文件结构创建失败,则直接从输入流解码图片
   if (file == null || !file.exists() || !file.canWrite()
     || !file.canRead()) {
    return BitmapFactory.decodeStream(input);
   }
  }
  return BitmapFactory.decodeFile(file.getAbsolutePath());
 }

 /**
  * 下载图片,输入InputStream
  *
  * @param urlString
  * @return
  * @throws IOException
  */
 private InputStream getBitmapInputStreamFromUrl(String urlString)
   throws IOException {
  URL url = new URL(urlString);
  URLConnection connection = url.openConnection();
  connection.setConnectTimeout(25000);
  connection.setReadTimeout(90000);
  return connection.getInputStream();
 }

 /**
  * 从输入流保存图片到文件系统
  *
  * @param fileName
  * @param input
  * @return
  */
 private File saveImage(InputStream input, String fileName) {
  if (fileName.trim().isEmpty() || input == null) {
   return null;
  }
  File file = new File(fileName);
  OutputStream output = null;
  try {
   file.getParentFile().mkdirs();
   if (file.exists() && file.isFile()) {
    file.delete();
   }
   if (!file.createNewFile()) {
    return null;
   }
   output = new FileOutputStream(file);
   byte[] buffer = new byte[4 * 1024];
   do {
    // 循环读取
    int numread = input.read(buffer);
    if (numread == -1) {
     break;
    }
    output.write(buffer, 0, numread);
   } while (true);
   output.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    output.close();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (Exception e2) {
    e2.printStackTrace();
   }
  }
  return file;
 }
}

本文章分享一个简单的android开发实现,功能是仿sina微博的listview更多分页按钮,有需要的朋友可以安看看。

因为百事查需要,需要制作这样的更多分页按钮,因为感觉新浪微博的更多分页按钮比较好,就尝试做了一下。
1、首先需要考虑布局,就是footer的布局,如下:

 代码如下 复制代码

<?xml version="1.0" encoding="UTF-8"?>

<LinearLayout android:layout_width="fill_parent" android:orientation="vertical"

android:layout_height="wrap_content" android:focusable="true"

xmlns:android="http://schemas.android.com/apk/res/android"

android:background="@drawable/loadmore" android:layout_centerVertical="true"

android:layout_centerHorizontal="true">

<!--

<Button android:id="@+id/loadMoreButton"

android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="更多" />

-->

<LinearLayout android:gravity="center" android:layout_height="wrap_content"

android:orientation="vertical" android:layout_width="fill_parent">

<ImageView android:background="@drawable/divider"

android:layout_height="2.0dip" android:layout_width="fill_parent" />

</LinearLayout>

<LinearLayout android:gravity="center" android:layout_gravity="center"

android:orientation="horizontal" android:layout_centerVertical="true"

android:layout_width="fill_parent" android:layout_height="60dip">

<TextView android:textSize="20.0sp" android:textColor="#ff545454"

android:gravity="center" android:id="@id/tv_msg" android:text="更多"

android:layout_width="fill_parent" android:layout_height="wrap_content"/>

<LinearLayout android:gravity="center" android:layout_height="wrap_content"

android:layout_gravity="center" android:orientation="horizontal"

android:id="@+id/llloading" android:layout_width="fill_parent">

<ProgressBar android:layout_gravity="center_vertical"

android:id="@id/footprogress" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:indeterminateBehavior="repeat"

style="?android:progressBarStyleSmallInverse" />

<TextView android:textColor="#ff000000" android:gravity="left|center"

android:padding="2.0px" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="读取中" />

</LinearLayout>

</LinearLayout>

</LinearLayout>
期中上面的一个@drawable/loadmore是一个选择器如下

<?xml version="1.0" encoding="utf-8"?>

<selector

xmlns:android="http://schemas.android.com/apk/res/android"

>

<item

android:state_pressed="false"

android:drawable="@drawable/listview_gradient"

>

</item>

<item

android:state_pressed="true"

android:drawable="@drawable/list_selector_background_pressed"

>

</item>

</selector>其中list_selector_background_pressed系统带的一个按钮在listview源代码中可以找到或sdk中也有

2、同时加载footer布局

list_footer = (LinearLayout)LayoutInflater.from(FansActivity.this).inflate(R.layout.sinalist_footer, null);

tv_msg = (TextView)list_footer.findViewById(R.id.tv_msg);

loading = (LinearLayout)list_footer.findViewById(R.id.llloading);

//btloadmore = (Button)list_footer.findViewById(R.id.loadMoreButton);

listView = getListView();

top_panel = (View)findViewById(R.id.fans_top);

top_btn_left = (Button)top_panel.findViewById(R.id.top_btn_left);

top_btn_right = (Button)top_panel.findViewById(R.id.top_btn_right);

top_title = (TextView)top_panel.findViewById(R.id.top_title);

listView.addFooterView(list_footer, null, false);//利用FooterVIew分页动态加载,参数false是不让选择
3、list_footer中增加按钮事件如下

list_footer.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

try {

// Toast.makeText(FansActivity.this, "我将消失了",

// Toast.LENGTH_SHORT).show();

//list_footer.setBackgroundColor(Color.YELLOW);

//list_footer.invalidate();

new FansThread().start();

//tv_msg.setEnabled(false);

tv_msg.setVisibility(View.GONE);// 隐藏更多提示的TextView

loading.setVisibility(View.VISIBLE);// 显示最下方的进度条

} catch (Exception e) {

e.printStackTrace();

}

}

});

效果如下

[!--infotagslink--]

相关文章

  • Android子控件超出父控件的范围显示出来方法

    下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
  • Android开发中findViewById()函数用法与简化

    findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20
  • Android模拟器上模拟来电和短信配置

    如果我们的项目需要做来电及短信的功能,那么我们就得在Android模拟器开发这些功能,本来就来告诉我们如何在Android模拟器上模拟来电及来短信的功能。 在Android模拟...2016-09-20
  • 夜神android模拟器设置代理的方法

    夜神android模拟器如何设置代理呢?对于这个问题其实操作起来是非常的简单,下面小编来为各位详细介绍夜神android模拟器设置代理的方法,希望例子能够帮助到各位。 app...2016-09-20
  • android自定义动态设置Button样式【很常用】

    为了增强android应用的用户体验,我们可以在一些Button按钮上自定义动态的设置一些样式,比如交互时改变字体、颜色、背景图等。 今天来看一个通过重写Button来动态实...2016-09-20
  • Android WebView加载html5页面实例教程

    如果我们要在Android应用APP中加载html5页面,我们可以使用WebView,本文我们分享两个WebView加载html5页面实例应用。 实例一:WebView加载html5实现炫酷引导页面大多...2016-09-20
  • 深入理解Android中View和ViewGroup

    深入理解Android中View和ViewGroup从组成架构上看,似乎ViewGroup在View之上,View需要继承ViewGroup,但实际上不是这样的。View是基类,ViewGroup是它的子类。本教程我们深...2016-09-20
  • 分享一段php获取linux服务器状态的代码

    简单的php获取linux服务器状态的代码,不多说-直接上函数:复制代码 代码如下:function get_used_status(){ $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");//获取某一时刻系统cpu和内存使用情况 $rs =...2014-05-31
  • Android自定义WebView网络视频播放控件例子

    下面我们来看一篇关于Android自定义WebView网络视频播放控件开发例子,这个文章写得非常的不错下面给各位共享一下吧。 因为业务需要,以下代码均以Youtube网站在线视...2016-10-02
  • Android用MemoryFile文件类读写进行性能优化

    java开发的Android应用,性能一直是一个大问题,,或许是Java语言本身比较消耗内存。本文我们来谈谈Android 性能优化之MemoryFile文件读写。 Android匿名共享内存对外A...2016-09-20
  • Android设置TextView竖着显示实例

    TextView默认是横着显示了,今天我们一起来看看Android设置TextView竖着显示如何来实现吧,今天我们就一起来看看操作细节,具体的如下所示。 在开发Android程序的时候,...2016-10-02
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • android.os.BinderProxy cannot be cast to com解决办法

    本文章来给大家介绍关于android.os.BinderProxy cannot be cast to com解决办法,希望此文章对各位有帮助呀。 Android在绑定服务的时候出现java.lang.ClassCastExc...2016-09-20
  • 服务器 UDP端口占用几千个的解决办法

    前一段时间使用NetStat命令查看服务器端口时,发现服务器udp端口开放了好多,最少在1000个以上,当时事情比较多,没有管它,今天终于有点时间,仔细检查了一下,排除了这个问题. ...2016-01-27
  • Android 实现钉钉自动打卡功能

    这篇文章主要介绍了Android 实现钉钉自动打卡功能的步骤,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下...2021-03-15
  • Android 开发之布局细节对比:RTL模式

    下面我们来看一篇关于Android 开发之布局细节对比:RTL模式 ,希望这篇文章对各位同学会带来帮助,具体的细节如下介绍。 前言 讲真,好久没写博客了,2016都过了一半了,赶紧...2016-10-02
  • PHP连接公司内部服务器的MYSQL数据库的简单实例

    “主机,用户名,密码”得到连接、“数据库,sql,连接”得到结果,最后是结果的处理显示。当然,数据库连接是扩展库为我们完成的,我们能做的仅仅是处理结果而已。...2013-09-29
  • 解决HttpPost+json请求---服务器中文乱码及其他问题

    这篇文章主要介绍了解决HttpPost+json请求---服务器中文乱码及其他问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-22
  • Android中使用SDcard进行文件的读取方法

    首先如果要在程序中使用sdcard进行存储,我们必须要在AndroidManifset.xml文件进行下面的权限设置: 在AndroidManifest.xml中加入访问SDCard的权限如下: <!--...2016-09-20
  • Android开发之PhoneGap打包及错误解决办法

    下面来给各位简单的介绍一下关于Android开发之PhoneGap打包及错误解决办法,希望碰到此类问题的同学可进入参考一下哦。 在我安装、配置好PhoneGap项目的所有依赖...2016-09-20