您的位置:首页 > 理论基础 > 计算机网络

简单介绍一下android studio中网络请求方法的步骤和环境搭建

2016-09-13 09:48 591 查看
程序员常用的几种网络请求方式:

1.httpUrlConnection:

        推荐,需要自己封装(在子线程或者线程池)

2.httpclient  appache:  

        不推荐使用

2.2AsyncHttpClient:

        框架  不推荐使用

3.volley框架:

        推荐

4.okhttp: 

        推荐,开源框架,没有封装,使用的时候需要自己封装(在子线程或者线程池)

5.retrofit: 

        对okHttp进行了非常好的封装

     先简单介绍一下okhttp(要下载依赖或者Jar包):

     打开github.com(或者谷歌搜索okhttp)下载:

compile 'com.squareup.okhttp3:okhttp:3.4.1'
     ——>打开app项目build.gradle——>在dependencies添加 

     

 


               以下为OKHttp的实例:

配置Xml文件:

<ImageView
android:id="@+id/iv"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
创建CommonUtils工具类

public class CommonUtils {
static Toast toast;
public static void showToast(Context context,String str){
if (toast==null){
//创建toast
toast=Toast.makeText(context,str,Toast.LENGTH_LONG);
}
toast.setText(str);
toast.show();
}
}
配置MainActivity:

public class MainActivity extends AppCompatActivity {
@InjectView(R.id.iv) //使用了Butterknife
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
final String imgPath = "图片";
//只有一个核心子线程
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
initOkhttpData(imgPath);
}
});
}

private void initOkhttpData(String imgPath) {
//创建okhttpclient对象
OkHttpClient client = new OkHttpClient();
//创建一个请求
Request request = new Request.Builder()
.url(imgPath)
.build();
//给okhttpClient传入一个请求,这个时候得到一个call
Call call = client.newCall(request);
//执行这个call
try {
//得到响应
Response response = call.execute();
int code = response.code();
if (code == 200) {
ResponseBody body = response.body();
byte[] bytes = body.bytes();
final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//UI线程
runOnUiThread(new Runnable() {
@Override
public void run() {
CommonUtils.showToast(getApplicationContext(), "成功");
iv.setImageBitmap(bitmap);
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
CommonUtils.showToast(getApplicationContext(), "失败");
}
});
}
} catch (IOException e) {
e.printStackTrace();
}

}
}
配置清单文件(添加网络权限):

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
在官网中有Demo:
OKHttp网址: 点击打开链接



     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息