访问网络的方式主要有 TCP(Socket 和ServerSocket)、Http/Https
与HttpURLConnection相比,HttpClient是由Apache组织提供的开源框架,HttpClient本质上就是将HttpURLConnection进行封装,使用起来更加方便。
HttpEntity对象:该对象中包含了服务器所有的返回内容。
借助EntityUtils的toString()方法或toByteArray()对 HttpEntity对象进行处理,也可以通过IO流对 HttpEntity对象进行操作。
/** * HttpClient通过get方式访问网络资源 * * @param url * @return */ public static String doGet_httpClient(String url) { // 打开浏览器: 初始化网络连接对象 HttpClient httpClient = (HttpClient) new DefaultHttpClient(); // 相当地址栏中输入url HttpGet httpGet = new HttpGet(url); try { // 执行:相当于按下回车 HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200) { InputStream is = entity.getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int c = 0; while ((c = bis.read(buffer)) != -1) { baos.write(buffer, 0, c); baos.flush(); } byte[] data = baos.toByteArray(); return new String(data); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
httpUrlConnection的GET方式访问网络
/** * get访问方式 * * @param url * @return 访问网络字符串形式返回 */ public static String doGet_HttpUrlCon(String url) { HttpURLConnection mHttpConn = null; try { // 创建一个资源定位符实例url URL httpUrl = new URL(url); // 打开指定url链接 mHttpConn = (HttpURLConnection) httpUrl.openConnection(); // 设置连接超时10秒 mHttpConn.setConnectTimeout(10 * 1000); // 设置 允许获得输入流 mHttpConn.setDoInput(true); // 设置请求方式 mHttpConn.setRequestMethod("GET"); // httpURLConnection.setRequestMethod("POST"); // 如果服务端返回结果为 200,则访问成功 if (mHttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = mHttpConn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int c = 0; while ((c = bis.read(buffer)) != -1) { baos.write(buffer, 0, c); baos.flush(); } byte[] data = baos.toByteArray(); return new String(data); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 断开链接 if (mHttpConn != null) { mHttpConn.disconnect(); } } return ""; }