android获取URLConnection和HttpClient网络请求响应码

简介:

http://www.open-open.com/lib/view/open1326868964593.html

有朋友问我网络请求怎么监听超时,这个我当时也没有没有做过,就认为是try....catch...获取异常,结果发现没有获取到,今天有时间,研究了一下,发现是从响应中来获取的对象中获取的,下面我把自己写的URLConnection和HttpClient网络请求响应码的实体共享给大家,希望对大家有帮助!

package com.zhangke.product.platform.http.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpHost;
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.conn.ClientConnectionRequest;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.zhangke.product.platform.util.NetworkUtil;

import android.content.Context;
import android.util.Log;
/**
 * @author spring sky
 * QQ 840950105
 * Email :vipa1888@163.com
 * 版权:spring sky
 * This class use in for request server and get server respnonse data
 * 
 *
 */
public class NetWork {
	/**
	 *   网络请求响应码
	 *   <br>
	 */
	private int responseCode = 1;
	/**
	 *  408为网络超时
	 */
	public static final int REQUEST_TIMEOUT_CODE = 408;
	
	/**
	 * 请求字符编码
	 */
	private static final String CHARSET = "utf-8";
	/**
	 * 请求服务器超时时间
	 */
	private static final int REQUEST_TIME_OUT = 1000*10; 
	/**
	 * 读取响应的数据时间
	 */
	private static final int READ_TIME_OUT = 1000*5;
	private Context context ;
	
	public NetWork(Context context) {
		super();
		this.context = context;
	}
	/**
	 * inputstream to String type 
	 * @param is
	 * @return
	 */
	public String getString(InputStream is )
	{
		String str = null;
		try {
			if(is!=null)
			{
				BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET));
				String line = null;
				StringBuffer sb = new StringBuffer();
				while((line=br.readLine())!=null)
				{
					sb.append(line);
				}
				str = sb.toString();
				if(str.startsWith("<html>"))   //获取xml或者json数据,如果获取到的数据为xml,则为null
				{
					str = null;
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	/**
	 * httpClient request type 
	 * @param requestURL
	 * @param map
	 * @return
	 */
	public InputStream requestHTTPClient(String requestURL,Map<String, String> map)
	{
		InputStream inputStream = null;
		/**
		 * 添加超时时间
		 */
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIME_OUT);
		HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);
		HttpClient httpClient = new DefaultHttpClient(httpParams);
		
		if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {
			HttpHost proxy = new HttpHost("10.0.0.172", 80);
			httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					proxy);
		}
		
		HttpPost httpPost = new HttpPost(requestURL);
		httpPost.setHeader("Charset", CHARSET);
		httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
		Iterator<String> it = map.keySet().iterator();
		while(it.hasNext())
		{
			String key = it.next();
			String value = map.get(key);
			Log.e("request server ", key+"="+value);
			list.add(new BasicNameValuePair(key, value));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(list,CHARSET));
			HttpResponse response =httpClient.execute(httpPost);
			inputStream = response.getEntity().getContent();
			responseCode = response.getStatusLine().getStatusCode();  //获取响应码
			Log.e("response code", response.getStatusLine().getStatusCode()+"");
//			Header[] headers =  response.getAllHeaders();    //获取header中的数据
//			for (int i = 0; i < headers.length; i++) {
//				Header h = headers[i];
//				Log.e("request heads", h.getName()+"="+h.getValue()+"     ");
//			}
		} catch (Exception e) {
			inputStream = null;
			e.printStackTrace();
		}
		return inputStream;
		
		
	}
	/**
	 * url request type 
	 * @param requestURL
	 * @param map
	 * @return
	 */
	public InputStream requestHTTPURL(String requestURL,Map<String,String> map )
	{
		InputStream inputStream = null;
		URL url = null;
		URLConnection urlconn = null;
		HttpURLConnection conn = null;
		try {
			url = new URL(requestURL);
			if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {
				Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
						new InetSocketAddress("10.0.0.172", 80));
				urlconn =  url.openConnection(proxy);
			}else{
				urlconn = url.openConnection();
			}
			conn = (HttpURLConnection) urlconn;
			if(conn!=null)
			{
				conn.setReadTimeout(READ_TIME_OUT);
				conn.setConnectTimeout(REQUEST_TIME_OUT);
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				conn.setRequestProperty("Charset", CHARSET);
				conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
				OutputStream os =  conn.getOutputStream();
				StringBuffer sb = new StringBuffer();
				Iterator<String> it =  map.keySet().iterator();
				while(it.hasNext())
				{
					String key = it.next();
					String value = map.get(key);
					Log.e("request server ", key+"="+value);
					sb.append(key).append("=").append(value).append("&");
				}
				String params = sb.toString().substring(0, sb.toString().length()-1);
				os.write(params.getBytes());
				os.close();
				inputStream = conn.getInputStream();
				Log.e("response code", conn.getResponseCode()+"");
				responseCode = conn.getResponseCode();  //获取响应码
//				Map<String, List<String>> headers =  conn.getHeaderFields();   //获取header中的数据
//				Iterator<String> is = headers.keySet().iterator();
//				while(is.hasNext())
//				{
//					String key = is.next();
//					List<String> values = headers.get(key);
//					String value = "";
//					for (int i = 0; i < values.size(); i++) {
//						value+= values.get(i);
//					}
//					Log.e("request heads",key+"="+value+"     ");
//				}
			}
		} catch (Exception e) {
			inputStream = null;
			e.printStackTrace();
		}
		return inputStream;
	}
	/**
	 *   网络请求响应码
	 */
	public int getResponseCode()
	{
		return responseCode ;
	}
	
	
}


相关文章
|
1月前
|
数据库 Android开发 开发者
构建高效Android应用:采用Kotlin协程优化网络请求处理
【2月更文挑战第30天】 在移动应用开发领域,网络请求的处理是影响用户体验的关键环节。针对Android平台,利用Kotlin协程能够极大提升异步任务处理的效率和简洁性。本文将探讨如何通过Kotlin协程优化Android应用中的网络请求处理流程,包括协程的基本概念、网络请求的异步执行以及错误处理等方面,旨在帮助开发者构建更加流畅和响应迅速的Android应用。
|
3月前
|
安全 API Android开发
Android网络和数据交互: 解释Retrofit库的作用。
Android网络和数据交互: 解释Retrofit库的作用。
38 0
|
3月前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
22 0
|
1天前
|
移动开发 Java Android开发
构建高效Android应用:采用Kotlin协程优化网络请求
【4月更文挑战第24天】 在移动开发领域,尤其是对于Android平台而言,网络请求是一个不可或缺的功能。然而,随着用户对应用响应速度和稳定性要求的不断提高,传统的异步处理方式如回调地狱和RxJava已逐渐显示出局限性。本文将探讨如何利用Kotlin协程来简化异步代码,提升网络请求的效率和可读性。我们将深入分析协程的原理,并通过一个实际案例展示如何在Android应用中集成和优化网络请求。
|
9天前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android&#39;s AsyncTask simplifies asynchronous tasks for brief background work, bridging UI and worker threads. It involves execute() for starting tasks, doInBackground() for background execution, publishProgress() for progress updates, and onPostExecute() for returning results to the main thread.
10 0
|
9天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
9 0
|
1月前
|
数据采集 前端开发 Java
利用Scala与Apache HttpClient实现网络音频流的抓取
利用Scala与Apache HttpClient实现网络音频流的抓取
|
3月前
|
JSON Java Android开发
Android网络和数据交互: 请解释Android中的JSON解析库,如Gson。
Android网络和数据交互: 请解释Android中的JSON解析库,如Gson。
24 0
|
4月前
|
XML JSON Android开发
[Android]网络框架之Retrofit(kotlin)
[Android]网络框架之Retrofit(kotlin)
56 0
|
Android开发
Android异步网络请求开源框架Volley
 Android开源框架Volley。Android平台中比较优秀的异步网络请求的开源框架。 官方链接地址:https://android.googlesource.com/platform/frameworks/volley  在这篇文章(系列)中有详细介绍。
760 0