OKhttp
来源:互联网 发布:matlab提取矩阵某一列 编辑:程序博客网 时间:2024/05/21 07:55
//// compile 'com.squareup.okhttp3:okhttp:3.9.0'
/****************************&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.okhttpdemo.MainActivity">
<Button
android:onClick="get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:onClick="getAsync"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="getAsync"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_marginLeft="3dp"
android:onClick="postAsync"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="postAsync"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
/&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/App
package com.example.okhttpdemo;
import android.app.Application;
import android.util.Log;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by hasee on 2017/9/7.
*/
public class App extends Application {
//OkHttpClient实例是唯一的, 所有的请求都会通过这个OkHttpClient,所以所有的请求都可能被拦截器拦截,
// 我们可以在这个必经之路,做一些通用的操作,比如打印日志.
private static OkHttpClient okHttpClient;
@Override
public void onCreate() {
super.onCreate();
//建议一个app只有一个OkHttpClient实例
okHttpClient = new OkHttpClient();
okHttpClient = okHttpClient.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor(new MyLogInterceptor())
.build();
}
public static OkHttpClient okHttpClient() {
return okHttpClient;
}
//拦截器,可以修改header,可以通过拦截器打印日志
public class MyLogInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.header("shenfen", "chinesse")
.build();
HttpUrl url = request.url();
String httpUrl = url.url().toString();
Log.e("TAG", "============" + httpUrl);
Response response = chain.proceed(request);
int code = response.code();
Log.e("TAG", "============response.code() == " + code);
return response;
}
}
}
/&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/MainActivity
package com.example.okhttpdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private OkHttpClient okHttpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
okHttpClient = App.okHttpClient();
}
//同步的get
public void get(View view) {
//request 设置url
final Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
new Thread(new Runnable() {
@Override
public void run() {
//通过newCall方法将request转换成call ,如果用execute()是同步执行
try {
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
//通过response.body().string()拿到服务器给我们的json
// String json = response.body().string();
//通过response.body().inputStream拿到服务器给我们的输入流 -- 主要用在大文件
// InputStream inputStream = response.body().byteStream();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "get成功", Toast.LENGTH_SHORT).show();
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "get失败", Toast.LENGTH_SHORT).show();
}
});
}
} catch (IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "get失败", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
//异步,所以的回调方法里面都是分线程.不能更新ui
public void getAsync(View view) {
//request 设置url
final Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "get失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String json = response.body().string();
//用Gson解析
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "get成功", Toast.LENGTH_SHORT).show();
}
});
} else {
//提示用户
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "get失败", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
//Post异步请求
public void postAsync(View view) {
FormBody formBody = new FormBody.Builder()
.add("type", "yuantong")
.add("postid", "11111111111")
.build();
final Request request = new Request.Builder()
.url(" http://www.kuaidi100.com/query")
.post(formBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "post失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String json = response.body().string();
//用Gson解析
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "post成功", Toast.LENGTH_SHORT).show();
}
});
} else {
//提示用户
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "get失败", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
/&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/配置
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.okhttpdemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
- OkHttp
- okhttp
- OkHttp
- OkHttp
- OkHttp
- okhttp
- OKHTTP
- okhttp
- Okhttp
- okHttp
- OkHttp
- okhttp
- Okhttp
- okhttp
- OkHttp
- okhttp
- okhttp
- okhttp
- Add Two Numbers
- svg初学——渐变
- 安卓开发setContentView
- JavaScript中String、Number以及Boolean三种基本类型的特殊用法
- CSDN 开始起航
- OKhttp
- 【书摘】三毛最深情的二十句话
- 数据库中的五种约束及其添加方法
- MySQL 获得当前日期时间(以及时间的转换)
- 代码合入
- UML
- 记首次项目经历心得
- 无限轮播的小圆点设置
- Android获取屏幕状态的方式