Android中的Http请求
程序的核心可以说是分为算法和数据结构两部分,说到底就是使用一定的方法(算法)处理数据(数据结构),算法是一种能力,需要不断的学习积累,而数据则需要获取,在移动设备上,不可能存储大量数据,所以就需要从服务器获取数据,和服务器进行数据交互,也就要用到Http请求。
Android4.0后所有网络方面的操作都不能在主线程执行 ! ! !
Android目前提供两种Http通信方式:HttpClient (org.appache.http) 和 HttpURLConnection (java.net)
HttpClient : 是Android SDK集成自Apache中,比较完善,全面支持Http协议,;(常用)
HttpURLConnection : 多用于发送和接收数据流形式的数据,传输数据量大,适合上传/下载文件;(用于简单的基于URL的请求、响应功能)
请 求 方 式又分为: HttpGet 请求和 HttpPost 请求
get方式 : 将参数连接在URL后面,各个参数之间用&连接;
post方式 : 使用根URL,将参数信息放在请求实体中发送;
HttpURLConnection实例
参考链接:http://blog.csdn.net/yanzi1225627/article/details/22222735
private String getURLResponse(String urlString){ HttpURLConnection conn = null; //连接对象 InputStream is = null; String resultData = ""; try { URL url = new URL(urlString); //URL对象 conn = (HttpURLConnection)url.openConnection(); //使用URL打开一个链接 conn.setDoInput(true); //允许输入流,即允许下载 conn.setDoOutput(true); //允许输出流,即允许上传 conn.setUseCaches(false); //不使用缓冲 conn.setRequestMethod("GET"); //使用get请求 is = conn.getInputStream(); //获取输入流,真正建立链接 InputStreamReader isr = new InputStreamReader(is); BufferedReader bufferReader = new BufferedReader(isr); String inputLine = ""; while((inputLine = bufferReader.readLine()) != null){ resultData += inputLine + "\n"; } } catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }finally{ if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(conn != null){ conn.disconnect(); } } return resultData; }
HttpClient (Get) 实例
链接:http://www.cnblogs.com/mengdd/p/3142442.html
// 使用GET方法发送请求,需要把参数加在URL后面,用?连接,参数之间用&分隔String url = baseURL + "?username=" + name + "&age=" + age;HttpGet httpGet = new HttpGet(url);// 生成请求对象HttpClient httpClient = new DefaultHttpClient();try{ // 发送请求 HttpResponse response = httpClient.execute(httpGet);//显示响应 showResponseResult(response);// 一个私有方法,将响应结果显示出来}catch (Exception e){ e.printStackTrace(); }
HttpClient (Post) 实例
链接:http://www.cnblogs.com/mengdd/p/3142442.html
try{ HttpEntity requestHttpEntity = new UrlEncodedFormEntity(pairList); // URL使用基本URL即可,其中不需要加参数 HttpPost httpPost = new HttpPost(baseURL); // 将请求体内容加入请求中 httpPost.setEntity(requestHttpEntity); // 需要客户端对象来发送请求 HttpClient httpClient = new DefaultHttpClient(); // 发送请求 HttpResponse response = httpClient.execute(httpPost); // 显示响应 showResponseResult(response); }catch (Exception e){ e.printStackTrace(); }
HttpClient (Post) 封装类
链接:http://www.cnblogs.com/hrlnw/p/4118480.html
/** * * 用于封装&简化http通信 * */public class PostRequest implements Runnable { private static final int NO_SERVER_ERROR=1000; //服务器地址 public static final String URL = "fill your own url"; //一些请求类型 public final static String ADD = "/add"; public final static String UPDATE = "/update"; public final static String PING = "/ping"; //一些参数 private static int connectionTimeout = 60000; private static int socketTimeout = 60000; //类静态变量 private static HttpClient httpClient=new DefaultHttpClient(); private static ExecutorService executorService=Executors.newCachedThreadPool(); private static Handler handler = new Handler(); //变量 private String strResult; private HttpPost httpPost; private HttpResponse httpResponse; private OnReceiveDataListener onReceiveDataListener; private int statusCode; /** * 构造函数,初始化一些可以重复使用的变量 */ public PostRequest() { strResult = null; httpResponse = null; httpPost = new HttpPost(); } /** * 注册接收数据监听器 * @param listener */ public void setOnReceiveDataListener(OnReceiveDataListener listener) { onReceiveDataListener = listener; } /** * 根据不同的请求类型来初始化httppost * * @param requestType * 请求类型 * @param nameValuePairs * 需要传递的参数 */ public void iniRequest(String requestType, JSONObject jsonObject) { httpPost.addHeader("Content-Type", "text/json"); httpPost.addHeader("charset", "UTF-8"); httpPost.addHeader("Cache-Control", "no-cache"); HttpParams httpParameters = httpPost.getParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); httpPost.setParams(httpParameters); try { httpPost.setURI(new URI(URL + requestType)); httpPost.setEntity(new StringEntity(jsonObject.toString(), HTTP.UTF_8)); } catch (URISyntaxException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 新开一个线程发送http请求 */ public void execute() { executorService.execute(this); } /** * 检测网络状况 * * @return true is available else false */ public static boolean checkNetState(Activity activity) { ConnectivityManager connManager = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); if (connManager.getActiveNetworkInfo() != null) { return connManager.getActiveNetworkInfo().isAvailable(); } return false; } /** * 发送http请求的具体执行代码 */ @Override public void run() { httpResponse = null; try { httpResponse = httpClient.execute(httpPost); strResult = EntityUtils.toString(httpResponse.getEntity()); } catch (ClientProtocolException e1) { strResult = null; e1.printStackTrace(); } catch (IOException e1) { strResult = null; e1.printStackTrace(); } finally { if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { statusCode=NO_SERVER_ERROR; } if(onReceiveDataListener!=null) { //将注册的监听器的onReceiveData方法加入到消息队列中去执行 handler.post(new Runnable() { @Override public void run() { onReceiveDataListener.onReceiveData(strResult, statusCode); } }); } } } /** * 用于接收并处理http请求结果的监听器 * */ public interface OnReceiveDataListener { /** * the callback function for receiving the result data * from post request, and further processing will be done here * @param strResult the result in string style. * @param StatusCode the status of the post */ public abstract void onReceiveData(String strResult,int StatusCode); }}
更多相关文章
- Android自定义动画类——实现3D旋转动画
- Android(安卓)数据存取试验 (二)
- Android(安卓)sd卡使用解说
- Android开发进阶(七)-- Android客户端访问PHP服务器的详细过程
- Android(安卓)media媒体库分析之:MediaProvider
- Android(安卓)内容提供器---创建内容提供器(设计数据存储)
- Android复杂数据模型序列化
- Android(安卓)BaseAadapter 异步加载图片方法
- Android(安卓)java.lang.RuntimeException: Parcelable encounte