主界面:
public class MainActivity extends AppCompatActivity {
private TextView textView;
private String path = "http://www.yulin520.com/a2a/forum/allTypeList?sign=376C5BFC22179A1B8FF3A86D4588B29F&pageSize=10&ts=1877785007&forumType=0&page=1";
// 将子线程消息传送到主线程
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
String json = (String) msg.obj;
Log.i("xxx",json);
Gson gson = new Gson();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// /获取资源ID
textView = (TextView) findViewById(R.id.textview);
getServerData();
boolean netWork = NetWorkUtils.isNetWork(this);
Log.i("xxx",netWork+"");
if(!netWork){
Toast.makeText(MainActivity.this, "网络未连接,请设置网络", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.settings.WIFI_SETTINGS"));// 进入无线网络配置界面
return;
}
}
private void getServerData() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
//建立连接对象
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//设置连接超时等待时间
con.setConnectTimeout(5000);
//设置请求方式
con.setRequestMethod("POST");
//判断是否连接成功
if ( con.getResponseCode()==200 ) {
//获得输入流
InputStream ins = con.getInputStream();
//封为工具类
String json = GetServerDataUtils.getServerData(ins);
Message message = new Message();
//给消息加标识
message.what = 0;
//把数据给消息
message.obj = json;
//通过handler发送消息
handler.sendMessage(message);
/*
抽取
//定义一个字节数组输出流
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//定义字节数组
byte[] bytes = new byte[1024];
//定义长度
int len = 0;
while ( (len=ins.read(bytes)) !=-1 ){
stream.write(bytes,0,len);
}
ins.close();
stream.close();
final String json = stream.toString();
*/
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
抽出的:
public class GetServerDataUtils {
public static String getServerData(InputStream inputStream) {
//定义一个字节数组输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//定义一个字节数组
byte[] buffer = new byte[1024];
//定义长度
int len = 0;
try {
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
inputStream.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
String string = bos.toString();
return string;
}
}
网络管理:
public class NetWorkUtils {
public static boolean isNetWork(Context context){
//连接管理权限
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获得当前连接的网络类型
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null){
return true;
}
return false;
}
}