在android studio中新建项目,打开build.gradle文件,在dependencies中添加:
compile 'com.squareup.okhttp:okhttp:2.6.0'
然后点击上方出现的黄色提示条:Sync Now,然后会看到下面进度条自动加载okhttp需要的jar,进度条加载成功后,点击项目名称右键Open Module Setting,可以看到项目已经添加上了com.squareup.okhttp:okhttp:2.6.0。
1.修改activity_main.xml文件,添加一个按钮,点击事件是doGet:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.imooc.sample.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET"
android:onClick="doGet"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
2.在MainActivity同一包中新建L类,用于封装日志打印操作:
package com.imooc.sample;
import android.util.Log;
/**
* Created by lsk on 2017/1/5.
*/
public class L {
private static final String TAG="Imooc_okhttp";
private static boolean debug=true;
public static void e(String msg){
if(debug){
Log.e(TAG,msg);//打印日志信息
}
}
}
3.在MainActivity.java中添加doGet()方法:
package com.imooc.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doGet(View view){
//1拿到okhttpclient对象
OkHttpClient okHttpClient=new OkHttpClient();
//2.构造request对象
Request.Builder builder=new Request.Builder();
Request request=builder.get().url("http://www.imooc.com/").build();
//3.将Request封装为call
Call call=okHttpClient.newCall(request);
//4.执行call
//Response response=call.execute();
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
L.e("onFailure:"+e.getMessage());
e.printStackTrace();
}
@Override
public void onResponse(Response response) throws IOException {
L.e("onResponse:");
String res=response.body().toString();
L.e(res);
}
});
}
}
response.body().toString();是get请求后返回的字符串。
总结下get请求分为4步:
1.拿到okhttpclient对象
2.构造request对象
3.将Request封装为call
4.执行call
5609

被折叠的 条评论
为什么被折叠?



