原生网络请求
public class MainActivity extends AppCompatActivity {
//接口地址
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);
//找控件
initView();
getServerData();
}
private void getServerData() {
//请求网络是耗时操作 也可以异步
//开子线程做耗时操作 android.os.NetworkOnMainThreadException
new Thread(new Runnable() {
@Override
public void run() {
//把接口地址包装成网络地址 联网需要加权限 android.permission.INTERNET
try {
URL url = new URL(path);
//建立连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置超时时间
connection.setConnectTimeout(5000);
//设置请求方式 换请求方式 get和post
connection.setRequestMethod("POST");
//判断响应码
if(connection.getResponseCode()==200){
//获取输入流
InputStream inputStream = connection.getInputStream();
//在子线程中直接更新UI 这种方式不建议使用
/* runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
}
});
*/
//定义一个字节数组输出流
/*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();
final String json = bos.toString();*/
//抽取成工具类
String json = GetServerDataUtils.getServerData(inputStream);
/*runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "json:"+json, Toast.LENGTH_SHORT).show();
Log.i("xxx",json);
}
});*/
//创建消息 第一种
Message message = new Message();
//给消息加标识
message.what = 0;
//把数据给消息
message.obj = json;
//通过handler发送消息
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//找控件
private void initView() {
TextView tv_title = (TextView) findViewById(R.id.tv_title);
}
}
别忘记加网络权限