AsyncTask+HttpClient
程序员文章站
2022-06-24 22:26:02
...
MainActivity主方法
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
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.util.List;
import java.util.concurrent.Executor;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.EntityUtilsHC4;
public class DemoActivity extends AppCompatActivity {
private ListView mLVContents;
private DemoAdapter mAdapter;
private @SuppressLint("StaticFieldLeak") AsyncTask<String, Integer, List<List<String>>> result;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
mLVContents = findViewById(R.id.lv_contents);
mAdapter = new DemoAdapter(this);
mLVContents.setAdapter(mAdapter);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
//网络判断
if (!NetUtil.hasNetwork(DemoActivity.this)) {
showNotNetworkDialog();
return;
}
//查询数据
initData();
}
});
mLVContents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
List<String> data = mAdapter.getItem(position);
Toast.makeText(DemoActivity.this, data.get(0) + ":" + data.get(1), Toast.LENGTH_LONG)
.show();
}
});
}
private void showNotNetworkDialog() {
new AlertDialog.Builder(this)
.setTitle("没有可用网络")
.setMessage("当前网络不可用,是否去设置")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Toast.makeText(DemoActivity.this, "去设置", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
String urlStr = "https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA";
private final int REQUEST_DATA_SUCCESS = 1;//请求数据成功
private final int SERA_DATA_SUCCESS = 2;//序列化(解析)数据成功
@SuppressLint("StaticFieldLeak") private void initData() {
//client
//请求对象
//构造模式
//链式调用
//执行请求
//结果
result = new AsyncTask<String, Integer, List<List<String>>>() {
@Override protected List<List<String>> doInBackground(String... strings) {
//网络请求数据 发布进度
//将String信息解析成Bean 发布发布进度
try {
//client
HttpClient client = HttpClients.createDefault();
//请求对象
//构造模式
HttpUriRequest request = RequestBuilder
.get()
.setUri(strings[0])
.build();
//链式调用
//执行请求
HttpResponse response = client.execute(request);
//结果
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
//后台操作过程中,发布进度。
//会导致onProgressUpdate调用
publishProgress(REQUEST_DATA_SUCCESS);
//gson使用反射解析Bean
Bean bean = new Gson().fromJson(result, Bean.class);
publishProgress(SERA_DATA_SUCCESS);
return bean.getResult();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//后台工作进度
@Override protected void onProgressUpdate(Integer... values) {
//if(values[0] == REQUEST_DATA_SUCCESS) {
// "请求数据成功";
//} else {
// "解析数据成功";
//}
Toast.makeText(DemoActivity.this,
values[0] == REQUEST_DATA_SUCCESS ?"请求数据成功":"解析数据成功",
Toast.LENGTH_SHORT).show();
}
@Override protected void onPostExecute(List<List<String>> s) {
mAdapter.setmDatas(s);
}
}.execute(urlStr);
}
private String stream2String(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) {
sb.append(tmp);
}
return sb.toString();
}
}
MyAdapter适配器
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class DemoAdapter extends BaseAdapter {
private List<List<String>> mDatas;
private Context mContext;
public DemoAdapter(Context context) {
this.mContext = context;
//初始化 为什么在这里写
mDatas = new ArrayList<>();
}
//外部调用 更新数据
public void setmDatas(List<List<String>> mDatas) {
this.mDatas = mDatas;
notifyDataSetChanged();
}
@Override public int getCount() {
return mDatas.size();
}
@Override public List<String> getItem(int position) {
List<String> item = mDatas.get(position);
//return item.get(0);
//return mDatas.get(position).get(0);
return item;
}
@Override public long getItemId(int position) {
return position;
}
//parent = ListView
@Override public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
//复用,不重复创建View
if(convertView == null) {
//convertView = View.inflate(mContext, R.layout.item, null);
convertView = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
vh = new ViewHolder();
vh.mIcon = convertView.findViewById(R.id.iv_icon);
vh.mText = convertView.findViewById(R.id.tv_text);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
//TODO 设置图片
//设置 数据
//vh.mText.setText(getItem(position));
vh.mText.setText(getItem(position).get(0));
return convertView;
}
class ViewHolder {
private ImageView mIcon;
private TextView mText;
}
}
Bean
import java.util.List;
public class Bean {
public List<List<String>> result;
public List<List<String>> getResult() {
return result;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="获取数据"
/>
<ListView
android:id="@+id/lv_contents"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/button"
/>
</android.support.constraint.ConstraintLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="获取数据"
/>
<ListView
android:id="@+id/lv_contents"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/button"
/>
</android.support.constraint.ConstraintLayout>
NetUtil.java判断工具类
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();
}
//判断是否是手机网络
public static boolean isMobileNetwork(Context context) {
//连接管理服务
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取到当前默认可用网络信息
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
//有网络设备 且 网络设备是手机网络
return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
}
推荐阅读