Apache接口(org.appache.http)----HttpClient,使用起来更方面更强大。一般来说,用这种接口。不过本文还是把第一种接口过一下。
任何一种接口,无外乎四个基本功能:访问网页、下载图片或文件、上传文件.本文示范的是访问网页和下载图片。HttpURLConnection继承自URLConnection类,用它可以发送和接口任何类型和长度的数据,且预先不用知道数据流的长度,可以设置请求方式get或post、超时时间。
切记加网络权限<uses-permission android:name="android.permission.INTERNET" />
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private String path;
private ListView listView;
/**
*在主线程中不能做耗时操作,只能在子线程完成
* 在子线程中不能做UI更新,只能在主线程完成
*/
@SuppressLint("HandlerLeak")
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
Bitmap bitmap= (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
break;
case 1:
String json= (String) msg.obj;
//Log.i("xxx", json);
Gson gson = new Gson();
//解析json
JsonBean jsonBean = gson.fromJson(json, JsonBean.class);
Log.i("xxx", jsonBean.toString());
ArrayList<Datas> date = jsonBean.getData();
listView.setAdapter(new MyAdapter(date,MainActivity.this));
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
imageView = findViewById(R.id.img);
listView = findViewById(R.id.listview);
//方法
getImage();//获取图片
getJsonData();//获取json
}
//获取json方法
private void getJsonData() {
new Thread(new Runnable() {
@Override
public void run() {
String path = "http://120.27.23.105/ad/getAd";
try {
//设置url
URL url = new URL(path);
//开启连接
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
//获取请求码
int code = connection.getResponseCode();
//判断网络连接
if (code == HttpURLConnection.HTTP_OK){
//获取服务器资源
InputStream inputStream = connection.getInputStream();
//输入流转输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len=inputStream.read(buffer))!=-1){
bos.write(buffer,0,len);
}
inputStream.close();
bos.close();
String json = bos.toString();
Message message = new Message();
message.what=1;
message.obj = json;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//获取image方法
private void getImage() {
//设置url
path = "http://gbres.dfcfw.com/Files/picture/20170306/size500/9FEA9AB789FA665C3418A84E561F3FCB.jpg";
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
//开启链接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//请求方式
connection.setRequestMethod("GET");
//获取请求码
int code = connection.getResponseCode();
//判断是
// 否请求成功
if (code==HttpURLConnection.HTTP_OK){
//获取服务器资源
InputStream inputStream = connection.getInputStream();
//图片资源给控件
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//创建消息
Message message = new Message();
message.obj = bitmap;
message.what=0;
//发送消息
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}