1.布局
(1)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="animtest.com.example.e531.week1_09month.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HttpClient请求"
android:id="@+id/btn_client"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HttpURLConnect请求"
android:id="@+id/btn_url"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="match_parent"
android:layout_below="@+id/btn_client"
android:layout_height="match_parent"
>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lv"
android:layout_alignParentLeft="true"
android:layout_gravity="center" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_gravity="center" />
</FrameLayout>
</RelativeLayout>
(2)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="animtest.com.example.e531.week1_09month.Main2Activity">
</RelativeLayout>
(3)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:id="@+id/img"
android:scaleType="fitXY"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_title"
android:layout_toRightOf="@id/img"
android:padding="5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_date"
android:layout_toRightOf="@+id/img"
android:layout_below="@id/tv_title"
android:padding="5dp"/>
</RelativeLayout>
2.main1
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<String, Void, String> {
@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<News> newsList=new ArrayList<News>();
try {
JSONObject obj=new JSONObject(s);
JSONArray array=obj.optJSONArray("newslist");
for(int i=0;i<array.length();i++){
JSONObject news=array.optJSONObject(i);
News ns=new 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();
}
}
Myalvde
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<News> newsList;
private Context context;
public MyLvAdapter(List<News> 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<String,Void,Bitmap>{
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类
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "animtest.com.example.e531.week1_09month"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile files('libs/gson-2.2.4.jar')
}