虽然github上有很多开源的,方便的jar报,用起来也很方便,但我们也需要了解其中的原理,如何自己不用第三方jar包来获取网络资源
主要代码如下: 因为联网是耗时的操作,所以需要另开一个线程来执行
new Thread(){
public void run() {
try { //首先声明url连接对象
URL url=new URL(path);
//获取HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setReadTimeout(5000);
//设置连接超时时间,毫秒为单位
connection.setConnectTimeout(5000); //http方式
connection.setRequestMethod("GET"); //设置http头属性
connection.setRequestProperty("apikey", "0a37fe84ecb7c6fe98ca3e8ba48b5f24");
//获取返回码//200为正常 404 找不到资源
int code = connection.getResponseCode();
if(code==200){ //获取字节流
InputStream inputStream = connection.getInputStream();
//解析字节流
BufferedReader bf=new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
StringBuilder sb=new StringBuilder();
String s=null;
while ((s=bf.readLine())!=null) {
sb.append(s+"\r\n");
} //解析json对象
JSONObject jsonObject = new JSONObject(sb.toString());
JSONArray jsonArray = jsonObject.getJSONArray("newslist");
for (int i = 0; i < jsonArray.length(); i++) {
news n= new news();
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
n.setTime(jsonObject2.getString("ctime"));
n.setTitle(jsonObject2.getString("title"));
n.setDescription(jsonObject2.getString("description"));
n.setPicUrl(jsonObject2.getString("picUrl"));
n.setUrl(jsonObject2.getString("url"));
list.add(n);
} }
} catch (Exception e) {
e.printStackTrace();
}
}; }.start();