Android系统中主要提供了两种方式来进行HTTP通讯,HttpURLConnection和HttpClient,几乎在任何项目的代码中咱们都能看到这两个类的身影,使用率很是高。java
不过HttpURLConnection和HttpClient的用法仍是稍微有些复杂的,若是不进行适当封装的话,很容易就会写出很多重复代码。因而乎,一些Android网络通讯框架也就应运而生,好比说AsyncHttpClient,它把HTTP全部的通讯细节所有封装在了内部,咱们只须要简单调用几行代码就能够完成通讯操做了。再好比Universal-Image-Loader,它使得在界面上显示网络图片的操做变得极度简单,开发者不用关心如何从网络上获取图片,也不用关心开启线程、回收图片资源等细节,Universal-Image-Loader已经把一切都作好了。这里简单介绍下HttpURLConnection和HttpClient的使用。至于框架后面会研究后,再介绍缓存
HttpClient的get使用cookie
HttpClient mClient; //http客户端 public static HttpEntity getEntity(String uri,ArrayList<BasicNameValuePair> params,int method) throws ClientProtocolException, IOException{ mClient=new DefaultHttpClient(); HttpUriRequest request=null; switch (method) { case HTTP_GET://get请求 StringBuilder sb=new StringBuilder(uri); //判断设置参数为不为空 if(null!=params&&!params.isEmpty()){ sb.append("?"); //设置配置参数 for (BasicNameValuePair param : params) { sb.append(param.getName()).append("=") .append(URLEncoder.encode(param.getValue(), "utf-8")).append("&"); } sb.deleteCharAt(sb.length()-1); //删除多余的 & } HttpGet get=new HttpGet(sb.toString()); //发送get请求 request=get; break; } //cookie缓存 HttpClientParams.setCookiePolicy(mClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY); //链接时间 mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); //设置请求超时时间 mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); //执行请求 得到响应 HttpResponse response = mClient.execute(request); if(response.getStatusLine().getStatusCode()==200){ //若是成功 返回HttpEntity 对象 return response.getEntity(); } return null; }
HttpURLConnection的post使用 post是 表单方式请求的网络
URL url =new URL(actionUrl); HttpURLConnection con=(HttpURLConnection)url.openConnection(); con.setReadTimeout(10 * 1000); //读数请求时间 con.setConnectTimeout(10 * 1000); //链接超时 /* 容许Input、Output,不使用Cache */ con.setDoInput(true); //之后就可使用conn.getInputStream().read(); con.setDoOutput(true); //之后就可使用conn.getOutputStream().write() get用不到这个 con.setUseCaches(false); //不使用缓存 /* 设置传送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); //保持tcp链接 con.setRequestProperty("Charset", "UTF-8"); //传输字符格式 UTF-8 con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); /* 设置DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";filename=\""+ newName +"\""+ end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream =new FileInputStream(uploadFile); /* 设置每次写入1024bytes */ int bufferSize =1024; byte[] buffer =new byte[bufferSize]; int length =-1; /* 从文件读取数据至缓冲区 */ while((length = fStream.read(buffer)) !=-1) { /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); /* 取得Response内容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b =new StringBuffer(); while( ( ch = is.read() ) !=-1 ) { b.append( (char)ch ); } /* 将Response显示于Dialog */ showDialog("上传成功"+b.toString().trim()); /* 关闭DataOutputStream */ ds.close();