AsyncTask 的 get post 封装
Posted yanliangjiang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AsyncTask 的 get post 封装相关的知识,希望对你有一定的参考价值。
1.get方法的封装AsyncTask
public class DBUTil2 {
public static interface Succee{
void onSuccee(String result);
}
public static interface Fail{
void onFail();
}
public static void getDataByGetInterface(final Map map, final Succee successCallback,
final Fail failCallback){
new AsyncTask<Void,Void,String>(){
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s!=null){
if(successCallback!=null){
successCallback.onSuccee(s);
}
}else{
if(failCallback!=null){
failCallback.onFail();
}
}
}
@Override
protected String doInBackground(Void... voids) {
String s = null;
try {
URL url = new URL((String) map.get("url"));
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
InputStream in=conn.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in));
s= bufferedReader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}.execute();
}
}
2.post方法的封装方法
public class DBUTil2 {
public static interface Succee{
void onSuccee(String result);
}
public static interface Fail{
void onFail();
}
public static void post(final Map map,final Succee succee ,final Fail fail ){
new AsyncTask<Void,Void,String>(){
@Override
protected void onPostExecute(String s) {
if (s!=null){
if (succee!=null){
succee.onSuccee(s);
}else {
if (fail!=null){
fail.onFail();
}
}
}
super.onPostExecute(s);
}
@Override
protected String doInBackground(Void... voids) {
String s = null;
String json = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL((String) map.get("url"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setUseCaches(false);
connection.setDoOutput(true);
outputStream = connection.getOutputStream();
JSONObject jsonObject = new JSONObject("jsonobject");
outputStream.write(jsonObject.toString().getBytes());
if (connection.getResponseCode()==200){
inputStream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((s=bufferedReader.readLine())!=null){
json+=s;
}
inputStream.close();
bufferedReader.close();
outputStream.flush();
outputStream.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json.substring(4,json.length());
}
}.execute();
}
以上是关于AsyncTask 的 get post 封装的主要内容,如果未能解决你的问题,请参考以下文章
OC HTTPRequest GET和POST请求的代码封装