您的位置:首页 > 移动开发 > Android开发

Android 利用异步任务AsyncTask发送post请求获取json数据

2016-12-06 09:52 921 查看
首先是AysncTask类:

/**
* Created by kfbmac3 on 16/7/8.
*/
/*
AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法。注意继承时需要设定三个泛型Params,
Progress和Result的类型,如AsyncTask<Void,Inetger,Void>:

Params是指调用execute()方法时传入的参数类型和doInBackgound()的参数类型
Progress是指更新进度时传递的参数类型,即publishProgress()和onProgressUpdate()的参数类型
Result是指doInBackground()的返回值类型

doInBackgound() 这个方法是继承AsyncTask必须要实现的,运行于后台,耗时的操作可以在这里做
publishProgress() 更新进度,给onProgressUpdate()传递进度参数
onProgressUpdate() 在publishProgress()调用完被调用,更新进度
*/
public class UpdateTextTask extends AsyncTask<Void,Integer,String> {
private Context context;
private String url;
private String postValue;
private TextView text;
UpdateTextTask(Context context , String string , String postValue , TextView text) {
this.context = context;
this.url = string;
this.postValue = postValue;
this.text = text;
}

/**
* 运行在UI线程中,在调用doInBackground()之前执行
* 该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置
*/
@Override
protected void onPreExecute() {
Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show();
}
/**
* 后台运行的方法,可以运行非UI线程,可以执行耗时的方法
* 这里的Void参数对应AsyncTask中的第一个参数
* 这里的String返回值对应AsyncTask的第三个参数
* 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改
* 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作
*/
@Override
protected String doInBackground(Void... params) {
int i=0;
while(i<10){
i++;
//publishProgress 更新进度,给onProgressUpdate()传递进度参数
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
String result = Common.postGetJson(url,postValue);
//第三个参数为String 所以此处return一个String类型的数据
return result;
}

/**
* 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)
* 运行在ui线程中,在doInBackground()执行完毕后执行,传入的参数为doInBackground()返回的结果
*/
@Override
protected void onPostExecute(String i) {
Toast.makeText(context,i,Toast.LENGTH_SHORT).show();
text.setText(i);
}

/**
* 在publishProgress()被调用以后执行,publishProgress()用于更新进度
* 这里的Intege参数对应AsyncTask中的第二个参数
* 在doInBackground方法当中,,每次调用publishProgress方法都会触发onProgressUpdate执行
* onProgressUpdate是在UI线程中执行,所有可以对UI空间进行操作
*/
@Override
protected void onProgressUpdate(Integer... values)
{
//第二个参数为Int
text.setText(""+values[0]);
}
}

接下来是发送http请求的方法:

public class Common {
public static String postGetJson(String url, String content) {
try {
URL mUrl = new URL(url);
HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
//设置链接超时时间
mHttpURLConnection.setConnectTimeout(15000);
//设置读取超时时间
mHttpURLConnection.setReadTimeout(15000);
//设置请求参数
mHttpURLConnection.setRequestMethod("POST");
//添加Header
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
//接收输入流
mHttpURLConnection.setDoInput(true);
//传递参数时需要开启
mHttpURLConnection.setDoOutput(true);
//Post方式不能缓存,需手动设置为false
mHttpURLConnection.setUseCaches(false);

mHttpURLConnection.connect();

DataOutputStream dos = new DataOutputStream(mHttpURLConnection.getOutputStream());

String postContent = content;

dos.write(postContent.getBytes());
dos.flush();
// 执行完dos.close()后,POST请求结束
dos.close();
// 获取代码返回值
int respondCode = mHttpURLConnection.getResponseCode();
Log.d("respondCode","respondCode="+respondCode );
// 获取返回内容类型
String type = mHttpURLConnection.getContentType();
Log.d("type", "type="+type);
// 获取返回内容的字符编码
String encoding = mHttpURLConnection.getContentEncoding();
Log.d("encoding", "encoding="+encoding);
// 获取返回内容长度,单位字节
int length = mHttpURLConnection.getContentLength();
Log.d("length", "length=" + length);
//            // 获取头信息的Key
//            String key = mHttpURLConnection.getHeaderField(idx);
//            Log.d("key", "key="+key);
// 获取完整的头信息Map
Map<String, List<String>> map = mHttpURLConnection.getHeaderFields();
if (respondCode == 200) {
// 获取响应的输入流对象
InputStream is = mHttpURLConnection.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
String msg = new String(message.toByteArray());
Log.d("Common", msg);
return msg;
}
return "fail";
}catch(Exception e){
return "error";
}
}
}

MainActivity:

public class MainActivity extends AppCompatActivity {

private Button btn;
private TextView text;
private String url = "http://192.168.24.104:3000/users";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
text = (TextView) findViewById(R.id.text);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Update();
}
});
}

private void Update(){
try{
String value = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode("anwei", "UTF-8") + "&" +
URLEncoder.encode("userfullname", "UTF-8") + "=" +
URLEncoder.encode("安威", "UTF-8");
UpdateTextTask updatetext = new UpdateTextTask(this, url, value , text);
updatetext.execute();
}catch(Exception e){
text.setText("error");
}
}
}


AsyncTask 异步任务相关文章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: