HTTP网络请求GSON解析网络不可用跳转到设置
//1主 mainactivity界面
package com.example.guoxinyu20181101;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.UrlQuerySanitizer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private Button button;
private ConnectionBase mBase;
private final int UPDATE_UI = 1;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_UI:
// List<ConnectionBean.Result> lists = (List<ConnectionBean.Result>) msg.obj;
List<List<String>> lists = (List<List<String>>) msg.obj;
mBase.setmlists(lists);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取资源id
listView = findViewById(R.id.lv_list);
button = findViewById(R.id.btn);
mBase = new ConnectionBase(MainActivity.this);
listView.setAdapter(mBase);
//点击加载数据
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//判断网络是否可用
if (!NetUtil.hasNetWork(MainActivity.this)) {
showNotNetWork();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
requestConnection();
}
}).start();
}
});
//点击监听
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
List<String> data = mBase.getItem(position);
Toast.makeText(MainActivity.this, data.get(0) + ":" + data.get(1), Toast.LENGTH_SHORT).show();
}
});
}
//弹框提示网络的方法
private void showNotNetWork() {
new AlertDialog.Builder(MainActivity.this)
.setTitle("无网络")
.setMessage("当前网络不可用,是否去设置?")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
startActivity(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
//加载数据的方法
private String urlStr = "https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA";
public void requestConnection() {
try {
//定义url地址
URL url = new URL(urlStr);
//打开连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//设置请求方式
urlConnection.setRequestMethod("GET");
//设置超时
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//获取请求码
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
String json = stream2String(urlConnection.getInputStream());
//得到gson
Gson gson = new Gson();
ConnectionBean connectionBean = gson.fromJson(json, ConnectionBean.class);
handler.sendMessage(handler.obtainMessage(UPDATE_UI, connectionBean.getResult()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
//字节流转换为字符流
public String stream2String(InputStream is) throws IOException {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder builder = new StringBuilder();
for (String tem = br.readLine(); tem != null; tem = br.readLine()) {
builder.append(tem);
}
return builder.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//适配器界面
package com.example.guoxinyu20181101;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ConnectionBase extends BaseAdapter {
private List<List<String>> lists;
private Context mContext;
public ConnectionBase(Context mContext) {
this.mContext = mContext;
//初始化
lists = new ArrayList<>();
}
public void setmlists(List<List<String>> lists) {
this.lists = lists;
notifyDataSetChanged();
}
@Override
public int getCount() {
return lists.size();
}
@Override
public List<String> getItem(int position) {
return lists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem, parent, false);
holder = new ViewHolder();
holder.text = convertView.findViewById(R.id.text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(getItem(position).get(0));
return convertView;
}
class ViewHolder {
private TextView text;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//判断是否有网络的类
package com.example.guoxinyu20181101;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetUtil {
//判断是否有网络
public static boolean hasNetWork(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo!=null && activeNetworkInfo.isAvailable();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//存放数据的BEAN类
package com.example.guoxinyu20181101;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetUtil {
//判断是否有网络
public static boolean hasNetWork(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo!=null && activeNetworkInfo.isAvailable();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guoxinyu20181101">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<!--跳转到网络设置的权限-->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</activity>
</application>
</manifest>