[Android]网络编程Httpclient类/HttpURLConnection类/okhttp框架
来源:互联网 发布:js md5解密 编辑:程序博客网 时间:2024/06/02 00:19
首先明确下网络编程需要一些基础概念
》输入输出流
InputStream之所以叫输入类,是因为它要把要需要读取的内容转化成输入流,再从它那里进行读取
OutputStream之所以叫输出类,是因为它首先需要与写入的目的地相关联,然后通过它进行写入。
输入是:把要读取的内容输入到输入流,在从输入流进行读取,所以是read()
输出是:把要输出的东西通过输出流输出到目的地,所以是write()
》关于Get和Post
一般来说,我们用到HTTP相关做网络请求,简便的我的理解,就是Get方式会将请求参数放到URL里,即追加到地址栏的方式,即请求网址+参数
所以get方式会限制数据字节长
而Post则是将数据放在编码里不会向外暴露,发送URL的时候,数据就这被发送的数据报里。不限制数据长度。
》URLConnection和HttpURLConnection
HttpURLConnection继承自URLConnection,差别在与HttpURLConnection仅仅针对Http连接
》状态码 表示服务器端返回的状态,如500表示错误,404表示资源不存在,我们一般关注200表示请求完成
======GET法=======HttpURLConnection===================
public class HttpUrlConnection { private static String PATH = "网址"; public HttpUrlConnection() { } public void save(){ InputStream inputStream = get();//这里就已经返回了请求到的数据 //...这里进行IO流的读写操作即可 } public InputStream get() { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL(PATH); if (url != null) { //openConnection()返回的是一个URLconnection对象,表示到url所引用的远程对象的连接 //所以用个已知的实现类httpURLConnection对象接收它吧 httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(3000);//设置网络超时时间 httpURLConnection.setDoInput(true);//打开输入流 //设置本次请求使用的方式 httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { //这个时候就可取数据了 inputStream = httpURLConnection.getInputStream();//得到一个输入流 } } } catch (Exception e) { e.printStackTrace(); } return inputStream; }}
======POST法=======HttpURLConnection===================
public class HttpPost { private static String PATH = "网址"; private static URL url; public HttpPost() { } static { try { url = new URL(PATH); } catch (MalformedURLException e) { e.printStackTrace(); } } public void Dopost() {//模拟发送 Map<String, String> params = new HashMap<String, String>(); params.put("username", "Tiffany"); params.put("password", "1234567"); httpPost(params, "utf-8"); } //params填写参数用 //encode 字节编码 public static String httpPost(Map<String, String> params, String encode) { //初始化的字符串用来做请求体 StringBuffer buffer = new StringBuffer(); OutputStream outputStream = null; InputStream inputStream = null; try { if (params != null && !encode.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { //为了把用户输入的参数追加到buffer里面 buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&"); } buffer.deleteCharAt(buffer.length() - 1);//删除最后的& try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3000);//设置连接超时的时候 connection.setRequestMethod("POST"); connection.setDoInput(true);//向服务端获取数据 connection.setDoOutput(true);//向服务器写数据 //获得上传信息的字节大小和长度//!!!!!这里已经开始封装内部数据了 byte[] mydata = buffer.toString().getBytes(); //设置请求体的类型 数据被编码为名称/值对。这是标准的编码格式 connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length",String.valueOf(mydata.length)); //获得输出流向服务器输出数据 outputStream = connection.getOutputStream(); outputStream.write(mydata);//把本地数据放进输出流,然后上传到服务器 //获得服务器响应的结果和状态码 int responseCode = connection.getResponseCode(); if (responseCode==200){ inputStream = connection.getInputStream(); return changeInputstream(inputStream,encode);//通过一个方法把输入流变成字符串 } } catch (IOException e) { e.printStackTrace(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } //将输入流变为指定编码的字符串 public static String changeInputstream(InputStream inputStream,String encode){ ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();//内存流 byte[] data = new byte[1024]; int len = 0; String result = ""; if (inputStream!=null){ try { while ((len=inputStream.read(data))!=-1){ arrayOutputStream.write(data,0,len);//把输出流写进去 } result = new String(arrayOutputStream.toByteArray(),encode); } catch (IOException e) { e.printStackTrace(); } } return result; }}
=============Httpclient=======================
创建代表请求的对象,如果需要发送GET请求,则创建HttpGet对象,如果需要发送POST请求,则创建HttpPost对象。
由于现在Android Studio 已经取消的对Httpclient的引用而且推荐使用HttpURLConnection,而且还存在OKhttp框架,这里就不多讲述了
//用HttpClient发送请求,分为五步//第一步:创建HttpClient对象70 HttpClient httpCient = new DefaultHttpClient();//第二步:创建代表请求的对象,参数是访问的服务器地址72 HttpGet httpGet = new HttpGet("http://www.baidu.com"); try {//第三步:执行请求,获取服务器发还的相应对象76 HttpResponse httpResponse = httpCient.execute(httpGet);//第四步:检查相应的状态是否正常:检查状态码的值是200表示正常78 if (httpResponse.getStatusLine().getStatusCode() == 200) { //第五步:从相应对象当中取出数据,放到entity当中80 HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串 }=============okhttp框架=======================
- [Android]网络编程Httpclient类/HttpURLConnection类/okhttp框架
- Android网络编程 HttpUrlConnection HttpClient AsyncTask
- Android网络编程之HttpUrlConnection、HttpClient
- Android网络编程HttpClient和HttpUrlConnection
- Android网络编程 HttpURLConnection,HttpClient,Asynchttpclient使用
- Android 网络编程之---HttpClient 与 HttpURLConnection 共用cookie
- Android 网络编程之---HttpClient 与 HttpURLConnection 共用cookie
- Android通过HttpURLConnection和HttpClient接口实现网络编程
- Android网络编程(二)HttpClient与HttpURLConnection
- Android 网络编程(2): HttpClient与HttpURLConnection
- Android网络编程(二)HttpClient与HttpURLConnection
- Android应用层(网络编程)二(HttpClient、HttpURLConnection)
- Android网络HttpURLConnection和HttpClient
- Android网络HttpURLConnection和HttpClient
- HttpClient与HttpURLConnection网络请求工具类
- Android4种网络连接方式HttpClient、HttpURLConnection、OKHttp、Volley
- Android 网络请求(一)HttpURLConnection+OkHttp
- android网络访问之HttpURLConnection vs OkHttp
- 设计模式原则
- Android:scaleType用法及参数含义
- C语言的内存陷阱1
- 创新在身边——收音机也可以了解天气
- 20. Valid Parentheses
- [Android]网络编程Httpclient类/HttpURLConnection类/okhttp框架
- 通用C# SqlHelper类库
- 在Thinkphp3.2 中使用PHPMailer 发送邮件
- Eclipse中的tab换为空格
- 数位dp裸题的套路
- 前端日期方法学习笔记
- 论docker中 CMD 与 ENTRYPOINT 的区别
- 杭电oj2090
- Linux新建用户误删除进入时su: warning: cannot change directory to /home/xx: No such file or director