//Mainactivity
package animtest.com.example.e531.week1_09month;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnClient = (Button) findViewById(R.id.btn_client);
Button btnUrl = (Button) findViewById(R.id.btn_url);
listView = (ListView) findViewById(R.id.lv);
progressBar=(ProgressBar) findViewById(R.id.progressBar);
//初使化为 看不见的状态
progressBar.setVisibility(View.INVISIBLE);
btnClient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//执行异步任务
MyTask myTask = new MyTask();
myTask.execute(new String[]{"https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10", "1"});
}
});
btnUrl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//执行异步任务
MyTask myTask = new MyTask();
myTask.execute(new String[]{"https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10", "2"});
}
});
}
class MyTask extends AsyncTask {
@Override
protected String doInBackground(String... params) {
String resultStr = "";
//得到请求的类型
String type = params[1];
if ("1".equals(type)) {//如果是"1" 执行 HttpGet请求
//因为请求的是https协议的网址,eclipse下使用HttpGet请求会报错,需要添加以下这行代码
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
//1.创建一个HttpClient对象
HttpClient hc = new DefaultHttpClient();
//2.创建httpGet对象
HttpGet hg = new HttpGet(params[0]);
try {
//3.执行请求
HttpResponse response = hc.execute(hg);
//4.判断结果码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//5.得到请求的结果
HttpEntity result = response.getEntity();
resultStr = EntityUtils.toString(result);
}
} catch (IOException e) {
e.printStackTrace();
}
} else if ("2".equals(type)) {//如果是2执行 HttpUrlConnection请求
try {
//1.创建Url对象
URL url = new URL(params[0]);
//2.打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//3.设置
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//4.得到响应码,进行判断
int code = connection.getResponseCode();
if (code == 200) {
//5.得到结果
InputStream inputStream = connection.getInputStream();
resultStr =streamToString(inputStream);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
}
return resultStr;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("zzz", s);
//进行解析,并显示到listView上
// Gson gson=new Gson();
// ResultBean resultBean=gson.fromJson(s,ResultBean.class);
List newsList=new ArrayList();
try {
JSONObject obj=new JSONObject(s);
JSONArray array=obj.optJSONArray("newslist");
for(int i=0;inew News();
ns.setCtime(news.optString("ctime"));
ns.setDescription(news.optString("description"));
ns.setPicUrl(news.optString("picUrl"));
ns.setTitle(news.optString("title"));
ns.setUrl(news.optString("url"));
newsList.add(ns);
}
} catch (JSONException e) {
e.printStackTrace();
}
//设置listview的适配器
MyLvAdapter adapter=new MyLvAdapter(newsList,MainActivity.this);
listView.setAdapter(adapter);
//请求完成时,进度条控件为不可见状态
progressBar.setVisibility(View.INVISIBLE);
//请求完成时,设置listview为可见状态
listView.setVisibility(View.VISIBLE);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//设置进度条为显示的状态
progressBar.setVisibility(View.VISIBLE);
//设置listview为不可见状态
listView.setVisibility(View.INVISIBLE);
}
}
/**
* 将流转换成字符串
* @param stream
* @return
*/
public String streamToString(InputStream stream) {
StringBuilder builder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "utf-8"));
String con;
while ((con = br.readLine()) != null) {
builder.append(con);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return builder.toString();
}
}
//适配器类
package animtest.com.example.e531.week1_09month;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* Created by e531 on 2017/10/8.
*/
public class MyLvAdapter extends BaseAdapter {
private List newsList;
private Context context;
public MyLvAdapter(List newsList, Context context) {
this.newsList = newsList;
this.context = context;
}
public int getCount() {
return newsList.size();
}
@Override
public Object getItem(int position) {
return newsList.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=View.inflate(context,R.layout.item,null);
holder=new ViewHolder();
holder.tvDate= (TextView) convertView.findViewById(R.id.tv_date);
holder.tvTitle= (TextView) convertView.findViewById(R.id.tv_title);
holder.img= (ImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
}else{
holder=(ViewHolder) convertView.getTag();
}
holder.tvDate.setText(newsList.get(position).getCtime());
holder.tvTitle.setText(newsList.get(position).getTitle());
//图片使用异步加载
MyPicTask myPicTask=new MyPicTask(holder.img);
myPicTask.execute(newsList.get(position).getPicUrl());
return convertView;
}
static class ViewHolder{
ImageView img;
TextView tvTitle;
TextView tvDate;
}
/**
* 使用异步任务请求图片
*/
class MyPicTask extends AsyncTask{
private ImageView imageView;
public MyPicTask(ImageView imageView){
this.imageView=imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap=null;
try {
//1.创建url对象
URL url=new URL(params[0]);
//2.打开连接
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
//3.设置
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setConnectTimeout(5000);
//4.得到结果码,并且判断
int code=connection.getResponseCode();
if(code==200){
//5.得到结果
InputStream inputStream=connection.getInputStream();
//将流转换成Bitmap对象
bitmap=BitmapFactory.decodeStream(inputStream);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
//显示图片
imageView.setImageBitmap(bitmap);
}
}
//Bean类
package animtest.com.example.e531.week1_09month;
import java.util.List;
/**
* Created by e531 on 2017/10/8.
*/
public class ResultBean {
private String code;
private String msg;
private List newslist;
@Override
public String toString() {
return "ResultBean{" +
"code='" + code + '\'' +
", msg='" + msg + '\'' +
", newslist=" + newslist +
'}';
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List getNewslist() {
return newslist;
}
public void setNewslist(List newslist) {
this.newslist = newslist;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
//Bean类
package animtest.com.example.e531.week1_09month;
/**
* Created by e531 on 2017/10/8.
*/
public class News {
private String ctime;
private String description;
private String picUrl;
private String title;
private String url;
@Override
public String toString() {
return "New{" +
"ctime='" + ctime + '\'' +
", description='" + description + '\'' +
", picUrl='" + picUrl + '\'' +
", title='" + title + '\'' +
", url='" + url + '\'' +
'}';
}
public String getCtime() {
return ctime;
}
public void setCtime(String ctime) {
this.ctime = ctime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}