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 ;
	}
	
	
}


相关文章
|
Java 程序员
JAVA程序员的进阶之路:掌握URL与URLConnection,轻松玩转网络资源!
在Java编程中,网络资源的获取与处理至关重要。本文介绍了如何使用URL与URLConnection高效、准确地获取网络资源。首先,通过`java.net.URL`类定位网络资源;其次,利用`URLConnection`类实现资源的读取与写入。文章还提供了最佳实践,包括异常处理、连接池、超时设置和请求头与响应头的合理配置,帮助Java程序员提升技能,应对复杂网络编程场景。
291 9
|
人工智能 Java 物联网
JAVA网络编程的未来:URL与URLConnection的无限可能,你准备好了吗?
随着技术的发展和互联网的普及,JAVA网络编程迎来新的机遇。本文通过案例分析,探讨URL与URLConnection在智能API调用和实时数据流处理中的关键作用,展望其未来趋势和潜力。
206 7
|
11月前
|
API 数据处理 Android开发
Android网络请求演变:从Retrofit到Flow的转变过程。
通过这个比喻,我们解释了 Android 网络请求从 Retrofit 到 Flow 的转变过程。这不仅是技术升级的体现,更是反映出开发者在面对并发编程问题时,持续探索和迭求更好地解决方案的精神。未来,还会有更多新的技术和工具出现,我们期待一同 witness 这一切的发展。
350 36
|
Java
【思维导图】JAVA网络编程思维升级:URL与URLConnection的逻辑梳理,助你一臂之力!
【思维导图】JAVA网络编程思维升级:URL与URLConnection的逻辑梳理,助你一臂之力!
216 1
|
9月前
|
Web App开发 缓存 JavaScript
Android网络小说阅读器的实现
小说阅读Demo,。此Demo使用Jsoup解析HTML,实现小说数据抓取(数据源自网络),并包含自定义View、六章小说缓存等功能,但未实现下载。项目还包括屏幕适配、字体设置等,借助第三方框架完成优化。以下是主页、详情页、阅读页等界面展示。
281 0
|
11月前
|
XML JavaScript Android开发
【Android】网络技术知识总结之WebView,HttpURLConnection,OKHttp,XML的pull解析方式
本文总结了Android中几种常用的网络技术,包括WebView、HttpURLConnection、OKHttp和XML的Pull解析方式。每种技术都有其独特的特点和适用场景。理解并熟练运用这些技术,可以帮助开发者构建高效、可靠的网络应用程序。通过示例代码和详细解释,本文为开发者提供了实用的参考和指导。
440 15
|
XML JSON 搜索推荐
【高手过招】JAVA网络编程对决:URL与URLConnection的高级玩法,你敢挑战吗?
【高手过招】JAVA网络编程对决:URL与URLConnection的高级玩法,你敢挑战吗?
321 0
|
Java 开发者
JAVA高手必备:URL与URLConnection,解锁网络资源的终极秘籍!
在Java网络编程中,URL和URLConnection是两大关键技术,能够帮助开发者轻松处理网络资源。本文通过两个案例,深入解析了如何使用URL和URLConnection从网站抓取数据和发送POST请求上传数据,助力你成为真正的JAVA高手。
297 11
|
JSON 安全 算法
JAVA网络编程中的URL与URLConnection:那些你不知道的秘密!
在Java网络编程中,URL与URLConnection是连接网络资源的两大基石。本文通过问题解答形式,揭示了它们的深层秘密,包括特殊字符处理、请求头设置、响应体读取、支持的HTTP方法及性能优化技巧,帮助你掌握高效、安全的网络编程技能。
295 9
|
JSON Java API
JAVA网络编程新纪元:URL与URLConnection的神级运用,你真的会了吗?
本文深入探讨了Java网络编程中URL和URLConnection的高级应用,通过示例代码展示了如何解析URL、发送GET请求并读取响应内容。文章挑战了传统认知,帮助读者更好地理解和运用这两个基础组件,提升网络编程能力。
269 5

热门文章

最新文章