android使用httpclient_httpurlcon_okhttp三种方式获取网络请求
1、httpclient 在android6.0后需要在build中android{加入useLibrary ‘org.apache.http.legacy’}
2、使用okhttp时需要导入okhttp包
代码如下:
package com.example.administrator.httpclient_httpurlcon_okhttp;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button_client;
private Button button_url;
private Button button_ok;
private ImageView imageView;
private final static String URL_IMG = “https://www.baidu.com/img/bd_logo1.png“;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
Bitmap bitmap = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
case 2:
Bitmap bitmap1 = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap1);
case 3:
Bitmap bitmap2 = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap2);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initListener();
}
private void init() {
button_client = findViewById(R.id.button_client);
button_url = findViewById(R.id.button_url);
button_ok = findViewById(R.id.button_okhttp);
imageView = findViewById(R.id.image);
}
private void initListener() {
button_client.setOnClickListener(this);
button_url.setOnClickListener(this);
button_ok.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_client:
new Thread(new Runnable() {
@Override
public void run() {
getHttpClient();
}
}).start();
break;
case R.id.button_url:
new Thread(new Runnable() {
@Override
public void run() {
getHttpUrl();
}
}).start();
break;
case R.id.button_okhttp:
new Thread(new Runnable() {
@Override
public void run() {
getHttpOKHttp();
}
}).start();
break;
default:
break;
}
}
private void getHttpClient() {
/**
* 1、创建httpclient对象
* 2、创建http请求
* 3、执行请求获取服务器返回结果
* 4、判断返回结果的状态码 200返回正确
* 5、从返回结果里出去相应数据
*/
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL_IMG);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
byte[] data = EntityUtils.toByteArray(entity);
Bitmap bitmap = dataToBit(data);
Message message = Message.obtain();
message.obj = bitmap;
message.what = 1;
handler.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void getHttpUrl() {
/**
* 1、获取url对象
* 2、创建httpurlconnection对象
* 3、设置超时时间
* 4、设置一系列请求方法
* 5、判断返回结果的状态码 200返回正确
* 6、从返回结果里出去相应数据
*/
try {
URL url = new URL(URL_IMG);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = inPutStreamToBit(inputStream);
Message message = Message.obtain();
message.obj = bitmap;
message.what = 1;
handler.sendMessage(message);
//直接在更新ui
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getHttpOKHttp() {
/**
* 1、初始化OkHttpClient 对象
* 2、初始化请求方法
* 3、创建Call对象
* 4、在onResponse里解析数据
*/
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(URL_IMG)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
Bitmap bitmap = inPutStreamToBit(inputStream);
Message message = Message.obtain();
message.obj = bitmap;
message.what = 3;
handler.sendMessage(message);
}
});
}
/**
* 使用BitmapFactory转换字节数组为bitmap对象
*
* @param data
* @return
*/
private Bitmap dataToBit(byte[] data) {
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}
private Bitmap inPutStreamToBit(InputStream inputStream) {
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
}