欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 请求网络接口实现方法

程序员文章站 2022-07-06 10:57:50
public class fragment01 extends fragment { private static final string tag = "fragment01----&q...

public class fragment01 extends fragment {

private static final string tag = "fragment01----";

private myhandler myhandler = new myhandler();

//判断网络状态

private final static int success = 0;

private final static int error = 1;

private listview listview;

@nullable

@override

public view oncreateview(@nonnull layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) {

view view = inflater.inflate(r.layout.fragment01_layout, container, false);

listview = view.findviewbyid(r.id.fragment01_listview);

return view;

}

@override

public void onactivitycreated(@nullable bundle savedinstancestate) {

super.onactivitycreated(savedinstancestate);

//4.获取网络数据

new thread() {

@override

public void run() {

try {

url u = new url(httpconfig.one_url);

httpurlconnection connection = (httpurlconnection) u.openconnection();

connection.setconnecttimeout(5000);

if (connection.getresponsecode() == 200) {

inputstream inputstream = connection.getinputstream();

//5.封装工具类

string json = commenutils.inputstream2string(inputstream);

//6.使用handler,发送数据

message message = myhandler.obtainmessage();

message.what = success;

message.obj = json;

myhandler.sendmessage(message);

}

} catch (exception e) {

e.printstacktrace();

}

}

}.start();

}

class myhandler extends handler {

@override

public void handlemessage(message msg) {

switch (msg.what) {

case success:

//成功

string json = (string) msg.obj;

log.d(tag, "handlemessage: " + json);

//导包gson

gson gson = new gson();

//如果json就是一个纯数组的解析方式

type listtype = new typetoken>(){}.gettype();

linkedlist list = gson.fromjson(json, listtype);//7.根据接口,生成javabean

//8.书写adapter进行显示

list item = list.get(0).getitem();

myadapter myadapter = new myadapter(getactivity(), item);

listview.setadapter(myadapter);

break;

}

}

}

}