当前位置:首页 > 开发 > 移动开发 > 正文

利用Android自带的http包进行网络请求

发表于: 2011-08-29   作者:dai_lm   来源:转载   浏览次数:
摘要: 目的是为了不依赖第三方的jar包进行网络请求(如:commons-httpclient.jar) 修改了一下,可以自定义请求的Header,增加了对POST表单数据的支持。 1. 建立一个连接配置类 class UserAgentConfig { public String host; public String scheme = "http";
目的是为了不依赖第三方的jar包进行网络请求(如:commons-httpclient.jar)

修改了一下,可以自定义请求的Header,增加了对POST表单数据的支持。

1. 建立一个连接配置类
class UserAgentConfig {
	public String host;
	public String scheme = "http";
	public int port = 80;
	public int timeoutConnection = 3000;
	public int timeoutSocket = 20000;
	public String username = "";
	public String password = "";
}

2. 封装请求类
public class HttpRequest {

	private String mUrl;
	private UserAgentConfig mConfig = null;
	private HashMap<String, String> mHeaders = null;
	private HttpEntity mBody = null;
	private int mStatus = -1;

	public HttpRequest(String url) {
		mUrl = url;
	}

	public void addHeader(String key, String value) {
		if (mHeaders == null)
			mHeaders = new HashMap<String, String>();

		mHeaders.put(key, value);
	}

	public void clearHeader() {
		mHeaders.clear();
		mHeaders = null;
	}

	public void setConfig(UserAgentConfig config) {
		mConfig = config;
	}

	public void setPostBody(List<BasicNameValuePair> body) {
		try {
			mBody = new UrlEncodedFormEntity(body, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void setPostBody(String body) {
		try {
			mBody = new StringEntity(body);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void execute() throws ClientProtocolException, IOException {
		httprequest();
	}

	public int getStatusCode() {
		return mStatus;
	}

	/**
	 * get "Stream" as response
	 * 
	 * @return response in stream
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public InputStream getStream() throws ClientProtocolException, IOException {

		HttpEntity entity = httprequest();
		InputStream ret = null;

		if (entity != null) {
			try {
				byte[] b = EntityUtils.toByteArray(entity);
				ret = new ByteArrayInputStream(b);
			} finally {
				release(entity);
			}
		}

		return ret;
	}

	/**
	 * get "String" as response
	 * 
	 * @return response in string
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String getString() throws ClientProtocolException, IOException {

		HttpEntity entity = httprequest();
		String ret = null;

		if (entity != null) {
			try {
				ret = EntityUtils.toString(entity);
			} finally {
				release(entity);
			}
		}

		return ret;
	}

	/**
	 * release connection resource
	 * 
	 * @param entity
	 */
	private static void release(HttpEntity entity) {
		try {
			entity.consumeContent();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * get "HttpEntity" as response
	 * 
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private HttpEntity httprequest() throws ClientProtocolException,
			IOException {

		System.out.println(mUrl);

		DefaultHttpClient client = null;
		HttpEntity entity = null;

		BasicHttpParams httpParameters = new BasicHttpParams();

		if (mConfig != null) {
			// set connection timeout
			HttpConnectionParams.setConnectionTimeout(httpParameters,
					mConfig.timeoutConnection);
		}

		client = new DefaultHttpClient(httpParameters);

		DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(
				3, true);
		client.setHttpRequestRetryHandler(retryHandler);

		// set username & password if available
		if (mConfig != null
				&& !(isEmpty(mConfig.username) && isEmpty(mConfig.password))) {
			AuthScope as = new AuthScope(mConfig.host, mConfig.port);
			UsernamePasswordCredentials upc = new UsernamePasswordCredentials(
					mConfig.username, mConfig.password);

			client.getCredentialsProvider().setCredentials(as, upc);
		}

		// check get or post method by params
		HttpRequestBase method = null;
		if (mBody == null) {
			method = new HttpGet(mUrl);
		} else {
			method = new HttpPost(mUrl);
			((HttpPost) method).setEntity(mBody);
		}

		// set request header
		if (mHeaders != null) {
			Iterator<?> iter = mHeaders.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<?, ?> entry = (Entry<?, ?>) iter.next();
				String key = (String) entry.getKey();
				String val = (String) entry.getValue();
				method.setHeader(key, val);
			}
		}

		// get response
		HttpResponse response = null;
		if (mConfig == null || isEmpty(mConfig.host) || isEmpty(mConfig.scheme)) {
			// only URL is available
			response = client.execute(method);
		} else {
			BasicHttpContext localContext = new BasicHttpContext();

			BasicScheme basicAuth = new BasicScheme();
			localContext.setAttribute("preemptive-auth", basicAuth);

			HttpHost targetHost = new HttpHost(mConfig.host, mConfig.port,
					mConfig.scheme);

			response = client.execute(targetHost, method, localContext);
		}

		mStatus = response.getStatusLine().getStatusCode();
		entity = response.getEntity();

		return entity;
	}

	/**
	 * Check the string is valuable or not
	 * 
	 * @param s
	 * @return true if s is null or s.length() == 0 false otherwise
	 */
	private boolean isEmpty(String s) {
		return s == null || s.length() == 0;
	}
}

3. 调用
GET请求
HttpRequest request = new HttpRequest("...");
request.execute();

UserAgentConfig config = new UserAgentConfig();
config.host = "...";
config.username = "...";
config.password = "...";

HttpRequest request = new HttpRequest("...");
request.setConfig(config);

System.out.println(request.getString());

POST请求
HttpRequest request = new HttpRequest("...");
request.addHeader("...", "...");
request.setPostBody("....");
request.execute();

System.out.println(request.getStatusCode());

利用Android自带的http包进行网络请求

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
原文地址:http://blog.csdn.net/forlong401/article/details/23538951 http://www.trinea.cn/andro
最新最准确内容建议直接访问原文:Android利用Fiddler进行网络数据抓包 主要介绍Android及IPhone手
转自Trinea的博客: http://www.trinea.cn/android/android-network-sniffer/ 主要介绍Android及IPho
最新最准确内容建议直接访问原文:Android利用Fiddler进行网络数据抓包 主要介绍Android及IPhone手
最新最准确内容建议直接访问原文:Android利用Fiddler进行网络数据抓包 主要介绍Android及IPhone手
最新最准确内容建议直接访问原文:Android利用Fiddler进行网络数据抓包 主要介绍Android及IPhone手
要 介绍Android及IPhone手机上如何进行网络数据抓包,比如我们想抓某个应用(微博、微信、墨迹天气)
主要介绍Android及IPhone手机上如何进行网络数据抓包,比如我们想抓某个应用(微博、微信、墨迹天气)
主要介绍Android及IPhone手机上如何进行网络数据抓包,比如我们想抓某个应用(微博、微信、墨迹天气)
发一下牢骚和主题无关: 在iOS开辟中有赫赫有名的ASIHttpRequest库,用来处置网络请求作操,天今要
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号