Http的get和post请求简单应用
2017-04-10 15:12
453 查看
网络请求中需要遵循http协议,而http有许多方法,大家一般最常用的就是post和get请求方法了!
其中,post和get都可以向服务器发送和请求数据,而我们一般都习惯用get请求数据,post发送数据!get方法是把数据拼接到请求行里面,我们可以直接看到里面的数据,相比较post不安全,但是简单,快捷(大小限制不超过2K)!post则是把要发送的数据转换成流的方式,大小不限制,上传给服务器,相比较get安全些!
基础定义和知识讲解不详细,大家可以参考大神的讲解,详细学习:
链接地址
其中本人AS版本2.3.如果你的AS版本低于2.2估计运行我的代码会报错,因为用到了最新的ConstraintLayout书写的布局,学习ConstraintLayout的链接我也放上去:
constraintlayout学习
本DEMO地址
效果图上两张:
下面我们直接上代码:
Xml布局代码就不放了都是用鼠标拉过来拉过去自动生成的代码
MainActivity代码:
代码注释很详细,其中用的是asynctask异步来处理的消息,没有用handler,以后会用!
然后就是自己封装的http和流解析的两个类了,
Stream类
可以直接调用类中方法即可!
最后Mainactivity 继承的是自己写的BaseActivity,用来控制进度条的显示,有兴趣可以下载demo进行测试!
下一篇要研究Handler和Thread的了,come on! 有错误多谢大家指正!!!
其中,post和get都可以向服务器发送和请求数据,而我们一般都习惯用get请求数据,post发送数据!get方法是把数据拼接到请求行里面,我们可以直接看到里面的数据,相比较post不安全,但是简单,快捷(大小限制不超过2K)!post则是把要发送的数据转换成流的方式,大小不限制,上传给服务器,相比较get安全些!
基础定义和知识讲解不详细,大家可以参考大神的讲解,详细学习:
链接地址
其中本人AS版本2.3.如果你的AS版本低于2.2估计运行我的代码会报错,因为用到了最新的ConstraintLayout书写的布局,学习ConstraintLayout的链接我也放上去:
constraintlayout学习
本DEMO地址
效果图上两张:
下面我们直接上代码:
Xml布局代码就不放了都是用鼠标拉过来拉过去自动生成的代码
MainActivity代码:
package com.btzh.myhttptest; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import CommonUntils.HttpUntils; public class MainActivity extends BaseActivity implements View.OnClickListener { private Button htmlbtn, picbtn,posthtmlbtn,postpichtn; private TextView textView; private ImageView imageView; int viewID = -1; HttpUntils Myuntils = new HttpUntils(); String XML_Url = "http://toutiao.sogou.com/?fr=qqxwtt"; String XMl_Url_test = "http://baike.sogou.com/v6234.htm?fromTitle=%E7%99%BE%E5%BA%A6"; String pic_Url = "http://d.ifengimg.com/mw978_mh598/p2.ifengimg.com/a/2017_15/65bdb6e5ca68409_size79_w930_h620.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initViews(); } /** * 初始化视图控件 */ private void initViews(){ htmlbtn = (Button) findViewById(R.id.button_gethtml); htmlbtn.setOnClickListener(this); picbtn = (Button) findViewById(R.id.button_getpic); picbtn.setOnClickListener(this); textView = (TextView)findViewById(R.id.textView); imageView = (ImageView)findViewById(R.id.imageView); posthtmlbtn = (Button)findViewById(R.id.button_posthtml); posthtmlbtn.setOnClickListener(this); postpichtn = (Button)findViewById(R.id.button_postpic); postpichtn.setOnClickListener(this); } @Override public void onClick(View v) { viewID = v.getId(); if (viewID == R.id.button_gethtml) { //get获取XMl信息 new MyXMlTask().execute(); }else if (viewID == R.id.button_getpic) { //get获取图片信息 showProgressDialog("正在加载图片!"); new MyAsyncTask().execute(); }else if (viewID == R.id.button_posthtml) { //post获取xml信息 new MyPostTask().execute(); }else if (viewID == R.id.button_postpic) { //post获取图片信息 new MyPostpicTask().execute(); }else { } } /** * get方法获取图片信息 */ private class MyAsyncTask extends AsyncTaskUntils<Object, Object, Object>{ @Override protected void onPostExecute(Object o) { super.onPostExecute(o); hideProgressDialog(); if (textView.getVisibility()==View.VISIBLE){ textView.setText(""); textView.setVisibility(View.GONE); } imageView.setVisibility(View.VISIBLE); imageView.setImageBitmap((Bitmap) o); } } /** * get 方法异步获取url数据 */ private class MyXMlTask extends AsyncTask<String, Integer,String>{ @Override protected void onPreExecute() { super.onPreExecute(); showProgressDialog(R.string.XMl_Toast); } @Override protected String doInBackground(String... params) { String string = Myuntils.URL_getString(XML_Url); return string; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); hideProgressDialog(); if (imageView.getVisibility()==View.VISIBLE){ imageView.setImageDrawable(null); imageView.setVisibility(View.GONE); } textView.setVisibility(View.VISIBLE); textView.setText(s); } } /** * Post 方法异步获取url数据 */ private class MyPostTask extends AsyncTask<String,Integer,String>{ @Override protected void onPreExecute() { super.onPreExecute(); showProgressDialog("Post正在加载网页信息!"); } @Override protected String doInBackground(String... params) { String postStr = Myuntils.URL_postString(XMl_Url_test); return postStr; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); hideProgressDialog(); if (imageView.getVisibility()==View.VISIBLE){ imageView.setImageDrawable(null); imageView.setVisibility(View.GONE); } textView.setVisibility(View.VISIBLE); textView.setText(s); } } /** * Post 方法异步获取url图片数据 */ private class MyPostpicTask extends AsyncTask<String,Object,Object>{ @Override protected void onPreExecute() { super.onPreExecute(); showProgressDialog("Post正在加载图片信息..."); } @Override protected Object doInBackground(String... params) { Bitmap postbitmap = Myuntils.URL_postitmap(pic_Url); return postbitmap; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); hideProgressDialog(); if (textView.getVisibility()==View.VISIBLE){ textView.setText(""); textView.setVisibility(View.GONE); } imageView.setVisibility(View.VISIBLE); imageView.setImageBitmap((Bitmap)o); } } }
代码注释很详细,其中用的是asynctask异步来处理的消息,没有用handler,以后会用!
然后就是自己封装的http和流解析的两个类了,
package CommonUntils; import android.graphics.Bitmap; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import CommonUntils.StreamTools; /** * Created by Lenovo on 2017/4/7. */ public class HttpUntils { private int HTTP_TIMEOUT_CONNECTION = 6*10000; private int HTTP_TIMER_READ = 1*10000; /** * 返回bitmap * @param httpUrl * @return */ public Bitmap URL_getbitmap(String httpUrl) { Bitmap bitmap = null; if ("" == httpUrl||null==httpUrl){ return null; } InputStream inputStream = null; try { //创建url对象 URL url = new URL(httpUrl); //打开connection连接 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); //设置请求方法 connection.setRequestMethod("GET"); //设置连接超时时间 connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION); //设置读取时间 connection.setReadTimeout(HTTP_TIMER_READ); //connection链接 connection.connect(); //判断是否连接成功,标识符号为200 if (HttpURLConnection.HTTP_OK!=connection.getResponseCode()) { return null; } //获取请求到的流 inputStream = connection.getInputStream(); //bitmap接收流对象(流转换为Bitmap格式对象) bitmap = StreamTools.getBitmap(inputStream); } catch (IOException e) { e.printStackTrace(); }finally { //一般最好写上,用来关闭前面开启的流对象,来减少内存占用 try { if (null!=inputStream){ inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return bitmap; } public String URL_getString(String httpUrl) { String string = ""; if ("" == httpUrl || null==httpUrl){ return "值为空!"; } InputStream inputStream = null; try { URL url = new URL(httpUrl); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION); connection.setReadTimeout(HTTP_TIMER_READ); connection.connect(); if (HttpURLConnection.HTTP_OK!=connection.getResponseCode()) { return "连接失败!"; } inputStream = connection.getInputStream(); string = StreamTools.getString(inputStream); } catch (IOException e) { e.printStackTrace(); }finally { try { if (null!=inputStream){ inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return string; } /** * post 请求数据返回 String * @param httpUrl * @return String */ public String URL_postString(String httpUrl) { if ("".equals(httpUrl) || null==httpUrl){ return null; } OutputStream outputStream = null; String postStr = ""; InputStream inputStream = null; try { //创建Url对象 URL url = new URL(httpUrl); //创建connection的url连接 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION); connection.setReadTimeout(HTTP_TIMER_READ); connection.setRequestMethod("POST"); //这两个方法post必须开启 connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); //这句话加上一直报错,说我已经connect成功服务器,是不是需要写在connection.connect();前面 // connection.setUseCaches(false); //data为需要传入服务器的数据,这里我们传空 String data = ""; //打开输入流 outputStream = connection.getOutputStream(); //往输入流中写入我们需要传入服务器的数据(格式为byte格式) outputStream.write(data.getBytes()); outputStream.flush(); //判断是否响应成功(其实就是Tcp/IP三次握手是否成功) if (HttpURLConnection.HTTP_OK!=connection.getResponseCode()){ return "连接失败"; } //获取服务器返回数据流 inputStream = connection.getInputStream(); //转换为String格式 postStr = StreamTools.getString(inputStream); } catch (IOException e) { e.printStackTrace(); }finally { //关闭各种流 try { if (outputStream!=null){ outputStream.close(); } if (inputStream!=null){ inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return postStr; } /** * post 请求数据返回Bitmap * @param httpUrl * @return Bitmap */ public Bitmap URL_postitmap(String httpUrl) { if ("".equals(httpUrl) || null==httpUrl){ return null; } OutputStream outputStream = null; Bitmap postBitmap = null; InputStream inputStream = null; try { URL url = new URL(httpUrl); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION); connection.setReadTimeout(HTTP_TIMER_READ); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); // connection.setUseCaches(false); String data = ""; outputStream = connection.getOutputStream(); outputStream.write(data.getBytes()); outputStream.flush(); if (HttpURLConnection.HTTP_OK!=connection.getResponseCode()){ return null; } inputStream = connection.getInputStream(); postBitmap = StreamTools.getBitmap(inputStream); } catch (IOException e) { e.printStackTrace(); }finally { try { if (outputStream!=null){ outputStream.close(); } if (inputStream!=null){ inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return postBitmap; } }
Stream类
package CommonUntils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by Lenovo on 2017/4/7. */ public class StreamTools { /** * inputStream 转换 Bitmap; * @param inputStream * @return bitmap */ public static Bitmap getBitmap(InputStream inputStream){ if (null == inputStream){ return null; } Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } /** * inputStream转String * @param inputStream * @return String */ public static String getString(InputStream inputStream){ if (null==inputStream){ return null; } InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(inputStreamReader); StringBuffer stringBuffer = new StringBuffer("UTF-8"); String line = null; try { while ((line = reader.readLine())!=null){ stringBuffer.append(line+"\n"); } } catch (IOException e) { e.printStackTrace(); return null; } return stringBuffer.toString(); } /** * inputStream 转 byte[] * @param inputStream * @return byte[] */ public static byte[] getBytes(InputStream inputStream) { String str = ""; byte[] readByte = new byte[1024]; int readCount = -1; try { while ((readCount = inputStream.read(readByte, 0, 1024)) != -1) { str += new String(readByte).trim(); } return str.getBytes(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * inputStream 转 Drawable * @param inputStream * @return Drawable */ public static Drawable getDrawable(InputStream inputStream){ if (null==inputStream){ return null; } Bitmap bitmap = getBitmap(inputStream); Drawable drawable = bitmap_Drawable(bitmap); return drawable; } // Bitmap转换成Drawable public static Drawable bitmap_Drawable(Bitmap bitmap) { if (null==bitmap){ return null; } BitmapDrawable bd = new BitmapDrawable(bitmap); Drawable drawable = (Drawable) bd; return drawable; } }
可以直接调用类中方法即可!
最后Mainactivity 继承的是自己写的BaseActivity,用来控制进度条的显示,有兴趣可以下载demo进行测试!
下一篇要研究Handler和Thread的了,come on! 有错误多谢大家指正!!!
相关文章推荐
- HttpPost 和Httpget 的简单应用
- "Android下使用HttpUrlConntion"进行最简单的get,post请求(包括创建服务器)
- 关于HTTP请求GET和POST的简单说明
- C++ 简单实现HTTP GET/POST 请求
- Java使用HttpURLConnection发送Get及Post请求简单过程
- HTTP协议下Android web应用GET和POST请求方法的请求、响应、传参
- C++ 简单实现HTTP GET/POST 请求
- ASIHTTPRequest 对GET POST 请求简单封装
- 简单记下httpclientjava实现get,post请求
- [Java]自定义Jar库,Http简单的Get和Post请求封装
- C++ 简单实现HTTP GET/POST 请求
- 一个简单地应用--从客户端向服务器发送数据.post,get.httpclientget,httpclinetpost,文件上传.
- C#模拟http 发送post或get请求的简单实例
- HttpClient发送Get、Post请求简单实践
- HTTP请求工具类,完成简单的GET POST请求(为了熟悉相关API)。
- C++ 简单实现HTTP GET/POST 请求
- 简单的HTTP请求post,get,put,delete,head方法的实现
- Android----------OkHttp网络请求框架Get和Post简单封装(泛型)
- ASIHTTPRequest 对GET POST 请求简单封装
- GO1.5实现简单的http并发请求,支持:GET、POST、HEAD、PUT