`
lizhou
  • 浏览: 109866 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

android http

阅读更多
package com.wizar.atool.net.http;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;

import android.os.AsyncTask;

import com.wizar.atool.log.Logger;

class HttpTask extends AsyncTask<Object, String, Object> {
	
	private static final Logger logger = Logger.getLogger();
	private HttpTool httpTool = null;
	private HttpClient httpClient = null;
	private HttpUriRequest httpRequest = null;
	private HttpTool.Task task = null;
	private boolean isAsyncTask = false;
	
	private HttpResponse httpResponse = null;
	private int rcode = 1;
	private Exception e;
	
	HttpTask(HttpTool httpTool) {
		this.httpTool = httpTool;
	}
	
	void setHttpElement(HttpClient httpClient, HttpUriRequest httpRequest) {
		this.httpClient = httpClient;
		this.httpRequest = httpRequest;
	}
	
	void setTask(HttpTool.Task task) {
		this.task = task;
	}
	
	void setIsAsyncTask(boolean isAsyncTask) {
		this.isAsyncTask = isAsyncTask;
	}

	@Override
	protected Object doInBackground(Object... params) {
		logger.debug("执行网络任务 开始...");
		
		try {
			httpResponse = httpClient.execute(httpRequest);
			rcode = 1;
		} catch (Exception e) {
			rcode = 2;
			this.e = e;
		}
		if (task != null) {
			task.doInBackground(httpResponse, rcode, e);
		}
		
		logger.debug("执行网络任务 结束...");
		if (isAsyncTask == false) {
			synchronized (httpTool) {
				httpTool.notify();
			}
		}
		
		return httpResponse;
	}
	
	HttpResponse getHttpResponse() {
		return this.httpResponse;
	}
	
	Exception getException() {
		return this.e;
	}
	
	int getRcode() {
		return this.rcode;
	}
}

 

调用类:

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

import com.wizar.atool.log.Logger;

public final class HttpTool {
	
	private static final Logger logger = Logger.getLogger();
	private List<Header> headerList = new ArrayList<Header>();
	private HttpClient mHttpClient = null;
	
	public HttpTool() {}
	
	/**
	 * 同步的http动作。业务逻辑在获取HttpResponse以后自己处理。<br/>
	 * 注意:连接没有关闭。请自行处理
	 * 
	 * @param httpClient HttpClient对象,可以为null
	 * @param httpRequest HttpUriRequest
	 * @return HttpResponse
	 * @throws Exception 连接发生异常,或处理HTTP消息发生异常时抛出此异常。
	 */
	public HttpResponse doSyncHttp(HttpClient httpClient, HttpUriRequest httpRequest) throws Exception {
		return doSyncHttp(httpClient, httpRequest, null);
	}
	
	/**
	 * 同步的http动作。业务逻辑可以在Task中处理,也可以在获取HttpResponse以后自己处理。<br/>
	 * 注意:连接没有关闭。请自行处理
	 * 
	 * @param httpClient HttpClient对象,可以为null
	 * @param httpRequest HttpUriRequest
	 * @param params 此参数可以在Task的doInBackground中使用,should be null. Becuase you can not use it.
	 * @param task 可以为null
	 * @return
	 * @throws Exception 连接发生异常,或处理HTTP消息发生异常时抛出此异常。
	 */
	public HttpResponse doSyncHttp(HttpClient httpClient, HttpUriRequest httpRequest, Task task) throws Exception {
		HttpTask httpTask = new HttpTask(this);
		mHttpClient = getHttpClient(httpClient);
		httpTask.setHttpElement(mHttpClient, httpRequest);
		httpTask.setTask(task);
		httpTask.execute(new Object[0]);
		
		logger.debug("等待执行任务 开始...");
		try {
			synchronized (this) {
				this.wait();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug("等待执行任务 结束...");
		
		int rcode = httpTask.getRcode();
		if (rcode == 1) {
			return httpTask.getHttpResponse();
		} else {
			throw httpTask.getException();
		}
	}
	
	/**
	 * 异步Http动作。业务逻辑可以在Task中处理<br/>
	 * 注意:连接没有关闭,请自行处理。
	 * 
	 * @param httpClient
	 * @param httpRequest
	 * @param params
	 * @param task
	 * @throws Exception
	 */
	public void doAsyncHttp(HttpClient httpClient, HttpUriRequest httpRequest, Task task) throws Exception {
		HttpTask httpTask = new HttpTask(this);
		mHttpClient = getHttpClient(httpClient);
		httpTask.setHttpElement(mHttpClient, httpRequest);
		httpTask.setTask(task);
		httpTask.setIsAsyncTask(true);
		httpTask.execute(new Object[0]);
	}
	
	/**
	 * 同步post方法。传文本参数。
	 * 
	 * @param url
	 * @param param 参数
	 * @param charset 参数编码方式
	 * @return
	 * @throws Exception
	 */
	public HttpResponse doPost(String url, String param, String charset) throws Exception {
		return doPost(url, new StringEntity(param, charset));
	}
	
	public void doAsyncPost(String url, String param, String charset, Task task) throws Exception {
		doAsyncPost(url, new StringEntity(param, charset), task);
	}
	
	/**
	 * 同步post方法。传递键值对列表。
	 *  
	 * @param url
	 * @param param NameValuePair list. the default subclass is BasicNameValuePair. The usage: new BasicNameValuePair(String name, String value);
	 * @param charset
	 * @return
	 * @throws Exception
	 */
	public HttpResponse doPost(String url, List<NameValuePair> param, String charset) throws Exception {
		return doPost(url, new UrlEncodedFormEntity(param, charset));
	}
	
	public void doAsyncPost(String url, List<NameValuePair> param, String charset, Task task) throws Exception {
		doAsyncPost(url, new UrlEncodedFormEntity(param, charset), task);
	}
	
	/**
	 * 同步post方法。传字节参数。
	 * 
	 * @param url
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public HttpResponse doPost(String url, byte[] param) throws Exception {
		return doPost(url, new ByteArrayEntity(param));
	}
	
	public void doAsyncPost(String url, byte[] param, Task task) throws Exception {
		doAsyncPost(url, new ByteArrayEntity(param), task);
	}
	
	/**
	 * 同步post方法。传流参数。
	 * 
	 * @param url
	 * @param instream
	 * @param length
	 * @return
	 * @throws Exception
	 */
	public HttpResponse doPost(String url, InputStream instream, long length) throws Exception {
		return doPost(url, new InputStreamEntity(instream, length));
	}
	
	public void doAsyncPost(String url, InputStream instream, long length, Task task) throws Exception {
		doAsyncPost(url, new InputStreamEntity(instream, length), task);
	}
	
	/**
	 * 同步post方法。传文件参数。
	 * 
	 * @param url
	 * @param file
	 * @param contentType
	 * @return
	 * @throws Exception
	 */
	public HttpResponse doPost(String url, File file, String contentType) throws Exception {
		return doPost(url, new FileEntity(file, contentType));
	}
	
	public void doAsyncPost(String url, File file, String contentType, Task task) throws Exception {
		doAsyncPost(url, new FileEntity(file, contentType), task);
	}
	
	public HttpResponse doPost(String url, HttpEntity entity) throws Exception {
		HttpPost httpUri = new HttpPost(url);
		for (Header header : headerList) {
			httpUri.addHeader(header);
		}
		httpUri.setEntity(entity);
		return doSyncHttp(null, httpUri);
	}
	
	public void doAsyncPost(String url, HttpEntity entity, Task task) throws Exception {
		HttpPost httpUri = new HttpPost(url);
		for (Header header : headerList) {
			httpUri.setHeader(header);
		}
		httpUri.setEntity(entity);
		doAsyncHttp(null, httpUri, task);
	}
	
	/**
	 * 同步get方法。
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public HttpResponse doGet(String url) throws Exception {
		HttpGet httpUri = new HttpGet(url);
		for (Header header : headerList) {
			httpUri.addHeader(header);
		}
		return doSyncHttp(null, httpUri);
	}
	
	/**
	 * 异步get方法。
	 * @param url
	 * @param task
	 * @throws Exception
	 */
	public void doAsyncGet(String url, Task task) throws Exception {
		HttpGet httpUri = new HttpGet(url);
		for (Header header : headerList) {
			httpUri.addHeader(header);
		}
		doAsyncHttp(null, httpUri, task);
	}
	
	private HttpClient getHttpClient(HttpClient httpClient) {
		if (this.mHttpClient == null) {
			if (httpClient == null) {
				mHttpClient = new DefaultHttpClient();
			} else {
				mHttpClient = httpClient;
			}
		}
		return mHttpClient;
	}
	
	public void setHttpClient(HttpClient httpClient) {
		this.mHttpClient = httpClient;
	}
	
	public void addHeader(Header header) {
		headerList.add(header);
	}
	
	public void addHeader(String name, String value) {
		headerList.add(new BasicHeader(name, value));
	}
	
	public void cleanAppendHeader() {
		headerList.clear();
	}
	
	public static interface Task {
		public Object doInBackground(HttpResponse httpResponse, int resultCode, Throwable cause);
	}
}

 

Logger:

package com.wizar.atool.log;

import android.util.Log;

public class Logger {

	public Logger() {
	}

	public static Logger getLogger() {
		return new Logger();
	}

	public void debug(String msg) {
		Log.d(createTag(), msg);
	}
	
	public void debug(String msg, Throwable tr) {
		Log.d(createTag(), msg, tr);
	}
	
	public void info(String msg) {
		Log.i(createTag(), msg);
	}
	
	public void info(String msg, Throwable tr) {
		Log.i(createTag(), msg, tr);
	}
	
	public void warn(String msg) {
		Log.w(createTag(), msg);
	}
	
	public void warn(String msg, Throwable tr) {
		Log.w(createTag(), msg, tr);
	}
	
	public void error(String msg) {
		Log.e(createTag(), msg);
	}
	
	public void error(String msg, Throwable tr) {
		Log.e(createTag(), msg, tr);
	}
	
	private String createTag() {
		StackTraceElement[] sts = Thread.currentThread().getStackTrace();
		if (sts == null) {
			return null;
		}
		for (StackTraceElement st : sts) {
			if (st.isNativeMethod()) {
				continue;
			}
			if (st.getClassName().equals(Thread.class.getName())) {
				continue;
			}
			if (st.getClassName().equals(this.getClass().getName())) {
				continue;
			}
			return st.getLineNumber() + ":" + st.getFileName();
		}
		return "";
	}
}

 

在activity中使用时,直接new对象就可以了。不用再考虑线程的问题。

 

 

 

分享到:
评论

相关推荐

    android HTTP接口测试软件

    在Android开发过程中,HTTP接口测试是一项重要的任务,用于验证服务器端API的功能以及客户端与服务器之间的数据交换。"android HTTP接口测试软件"是一个专为Android平台设计的小型应用程序,旨在简化这个过程。它...

    androidhttp通讯jar包

    androidhttp,互联网通讯必须

    android http通信demo

    android 当中涉及到网络编程的部分经常会用到http通信,同时android也为我么您提供了HttpUrlConnection接口和HttpClient接口,大大的方便了开发。Http通信又分为两种方式:get和post,get可以uoqu静态页面,传入参数...

    android HTTP通信例子(json数据传递)

    在Android应用开发中,HTTP通信是连接客户端与服务器端的重要桥梁,主要用于数据交换、文件上传和下载等操作。本示例将重点讲解如何在Android应用中实现基于HTTP的JSON数据传递,以及如何处理文件的上传和下载。 ...

    android http请求及缓存框架GalHttprequest

    android http请求及缓存框架GalHttprequest

    android http 请求将经纬度查询为地址信息类

    android http 请求将经纬度查询为地址信息类 详细内容查看blog.csdn.net/lxm247

    Android Http简易封装

    该实例用于博客《Android之Http网络编程四》http://www.cnblogs.com/scetopcsa/p/4021196.html 实例并不是一个完整的、可直接使用的Http操作的封装,只算是提供了一种完善Http操作的思路吧。

    Android Http 接口封装包括调用WebService

    Android 调用Http接口的封装。由于Android要求Http调用必须在线程当中,所以本人就封装了一个工具类,该工具类即支持阻塞/同步调用,也支持异步调用,便于调用Http接口方便。

    Android Http URL Connection获取数据并JSON解析

    在Android开发中,网络通信是应用与服务器交互的重要方式,其中`HttpURLConnection`是Java标准库提供的一种轻量级的HTTP请求方式。本教程将深入探讨如何使用`HttpURLConnection`从远程服务器获取数据,并结合JSON...

    Android http库Netroid

    Android http库Netroid jar包

    android Http请求库,用于整合所有请求与返回

    该http请求库,用于将所有的http请求和返回参数整合到一起,方便以后进行调用,和更改。

    例子代码 android http://blog.csdn.net/qq282133/article/details/7616809

    【标题】"例子代码:Android HTTP网络请求实践" 在Android应用开发中,网络通信是必不可少的一部分,本示例代码着重讲解了如何在Android环境中进行HTTP请求。博客文章"android ...

    android http 工具类 get post

    android http 工具类 get post

    android http服务器

    在Android平台上实现一个HTTP服务器,主要是为了让Android设备能够作为一个服务器端点,允许其他设备通过HTTP协议访问和交互数据。这通常用于调试、测试或者在没有传统服务器环境的情况下分享或接收数据。Android ...

    android端HttpServer的实现

    下这个吧 , https://download.csdn.net/download/dami_lixm/11341046 android端HttpServer的实现,PC端通过浏览器访问android端SD卡上文件的功能

    Android Http简单应用源码.zip项目安卓应用源码下载

    Android Http简单应用源码.zip项目安卓应用源码下载Android Http简单应用源码.zip项目安卓应用源码下载 1.适合学生毕业设计研究参考 2.适合个人学习研究参考 3.适合公司开发项目技术参考

    android Http get_post

    android Http get_post get方法封装 post方法封装

    android http 多请求异步封装

    本demo主要对异步请求封装 可用作基本项目框架来使用 网络请求等等小细节已经ok 如有需要请进一步更改 1)封装HttpClient ...博客链接使用说明:http://blog.csdn.net/vpingchangxin/article/details/23375461

    Android通过http实现登录、注册、下载

    在Android应用开发中,通过HTTP协议与服务器进行数据交互是一种常见的做法,特别是在实现登录、注册和文件下载等基本功能时。以下将详细讲解这个过程涉及的关键知识点。 1. **HTTP协议**:HTTP(HyperText Transfer...

    Android http图片上传工具类

    该类传入 Bitmap 服务器访问地址 图片名字 服务器的key

Global site tag (gtag.js) - Google Analytics