OkHttp的使用
来源:互联网 发布:nginx url 跳转 编辑:程序博客网 时间:2024/06/04 18:48
android开发中比较经常使用的一个http框架是Volley,这个框架是基于httpclient开发的,在android6.0中,google将httpclient这个API废弃掉了。发送http请求时使用httpurlconnection这个API。OkHttp是基于httpurlconnection的一个框架。
十分简陋的UI
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="${relativePackage}.${activityClass}" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="ok http测试" android:textSize="24sp" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="get" android:text="GET" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="post" android:text="POST" /></LinearLayout>
GET请求
public void get(View view) {OkHttpClient client=new OkHttpClient();Request request=new Request.Builder().url("http://192.168.1.100:8000/okhttp/").build();Call call=client.newCall(request);call.enqueue(new Callback() {@Overridepublic void onResponse(Response response) throws IOException {System.out.println(response.body().string());}@Overridepublic void onFailure(Request request, IOException arg1) {}});}
POST请求
public void post(View view) {String str="123";MediaType type=MediaType.parse("Content-Type:text/plain;charset:utf-8;");OkHttpClient client=new OkHttpClient();RequestBody body=RequestBody.create(type, str);Request request=new Request.Builder().url("http://192.168.1.100:8000/okhttp/").post(body).build();Call call=client.newCall(request);call.enqueue(new Callback() {@Overridepublic void onResponse(Response response) throws IOException {System.out.println(response.body().string());}@Overridepublic void onFailure(Request arg0, IOException arg1) {}});}
在数据交换中可以灵活使用数据交换格式,这里使用的是字符串。OkHttp构造完请求体就可以回调了,使用过程和Volley类似。在onResponse回调请求成功的结果,在onFailure回调请求失败的结果。
注:OkHttp的jar包内部依赖okio,两个要一起引用
0 0
- OkHttp的使用介绍
- OkHttp的简单使用
- OKHttp的简单使用
- android OkHttp的使用
- OkHttp的使用
- OkHttp的使用教程
- OkHttp的使用
- OkHttp的使用
- 高效的使用okhttp
- OkHttp的使用
- okhttp 的使用
- okhttp的第一次使用
- 关于OkHttp的使用
- okhttp的使用
- okhttp框架的使用
- OkHttp的使用
- okhttp的使用
- OKHttp的简单使用
- ionic 底部tab模块切换,使用背景图片
- JavaMail--基础类详解
- 常用的一些算法稳定性分析
- C# Strings
- ios developer tiny share-20160920
- OkHttp的使用
- 悬浮窗错误android.view.WindowManager$BadTokenException: permission denied for this window type
- js中的call函数
- 多个时间段统计
- json解析数组
- specified for property 'resourceFile' does not exist
- 在Neatbeans中使用JUnit4的学习时的总结
- Nagios和商业开源网管软件SugarNMS的功能介绍和区别
- Android 的透明色的代码