前言:
最近在做安卓新项目 但是要用到老技术 有点尴尬哈 因为之前手写的网络框架都是开一个线程然后用handler来实现线程之前的通信 现在我改了用 AsyncTask 来实现:做个笔记 因为是很老的技术 我就不当时博客了
效果图
具体实现:
网络连接
ini
package com.example.myapplication.http;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
* Created by xuqing on Date: 2022/11/2
*/
public class NetWorkRequest {
private int dkpdpConnectTime =10000;
private int dkpdpReadTime =10000;
/**
* ch
* @param requestUrl
* @param requestMethod
*/
public NetResponse qecrnNetWordRequst(String requestUrl, String requestMethod, String contextType, String body, Map<String, String> headerMap){
HttpURLConnection connection = null;
try {
URL url = new URL(requestUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(dkpdpConnectTime);
connection.setReadTimeout(dkpdpReadTime);
connection.setRequestMethod(requestMethod);
connection.setDoInput(true);//可读入
connection.setDoOutput(true);//可写出
connection.setUseCaches(false);//不缓存
if(!TextUtils.isEmpty(contextType)){
connection.setRequestProperty("Content-Type", contextType);
}
if(headerMap!=null && headerMap.size()>0){
for (String key:headerMap.keySet()){
connection.setRequestProperty(key,headerMap.get(key));
}
}
connection.connect();//建立连接
if(!TextUtils.isEmpty(body)){
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
if(writer!=null){
writer.write(body);
writer.close();
}
}
return qecrnGetNetResponse(connection);
} catch (Throwable e) {
e.printStackTrace();
return qecrnExceptionResponse(connection,e);
}
}
/**
* 正常返回,获取response 对象
* @param conn
* @return
*/
private NetResponse qecrnGetNetResponse(HttpURLConnection conn){
NetResponse response = new NetResponse();
try {
if(conn == null){
return null;
}
response.dkpdpResponseCode = conn.getResponseCode();
if(response.dkpdpResponseCode == HttpURLConnection.HTTP_OK){
response.dkpdpResponseContent = qecrnGetResponeString(conn.getInputStream());
response.dkpdpResponseCode = 200;//强制修改为200,判断200为成功接收就好了。
}else{
response.dkpdpResponseContent = qecrnGetResponeString(conn.getErrorStream());
}
} catch (Throwable e) {
response.dkpdpResponseCode = -1;
response.dkpdpResponseContent = e.getMessage();
e.printStackTrace();
}
return response;
}
/**
* 异常返回,获取response 对象
* @param conn
* @param e
* @return
*/
private NetResponse qecrnExceptionResponse(HttpURLConnection conn, Throwable e){
if(conn != null){
conn.disconnect();
}
if(e == null){
return null;
}
e.printStackTrace();
NetResponse response = new NetResponse();
response.dkpdpResponseCode = -2;
response.dkpdpResponseContent = e.getMessage();
return response;
}
private String qecrnGetResponeString(InputStream is){
String buf;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
buf = sb.toString();
return buf;
} catch (Throwable e) {
return "";
}
}
}
异步任务 GET
typescript
package com.example.myapplication.http;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by kunge hu on 2016/11/1.
*/
public class GetTask extends AsyncTask<Void, Void, String> {
private static final String TAG = "GetTask";
private HttpRequestCallBack listener;
private String url;
private Map<String, String> getmapparams;
private String type;
/**
*
* @param url
* @param listener
*/
public GetTask( String url,HttpRequestCallBack listener) {
this.listener = listener;
this.url = url;
}
/***
*
* @param url
* @param type
* @param getmapparams
* @param listener
*/
public GetTask(final String url, final String type, final Map<String, String> getmapparams, HttpRequestCallBack listener) {
this.url = url;
this.listener = listener;
this.getmapparams=getmapparams;
this.type=type;
}
@SuppressLint("NewApi")
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
try {
String geturl="";
if(getmapparams!=null){
geturl= RequestUtil.clwuyGetUrl(url,getmapparams);
}else{
geturl=url;
}
NetWorkRequest request = new NetWorkRequest();
Map<String, String> headerMap=new HashMap<>();
headerMap.put("x-method","get");
headerMap.put("x-request",type);
String contextType="application/json;charset=utf-8";
NetResponse response =request.qecrnNetWordRequst(geturl,"GET",contextType,"",headerMap);
Log.e(TAG, "doInBackground:response "+response.dkpdpResponseContent );
if(response.dkpdpResponseCode==200){
return response.dkpdpResponseContent;
}else{
return null;
}
} catch (Exception e) {
Log.e("kunge.hu", "GetTask Exception:" + e.toString());
}
return null;
}
@SuppressLint("NewApi")
@Override
protected void onPostExecute(String t) {
try {
if(!TextUtils.isEmpty(t)){
JSONObject jsonObject=new JSONObject(t);
listener.clwuyHttpCallBackListener(t);
}else{
Log.e(TAG, "onPostExecute: "+"网络服务器失败" );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
异步任务post
typescript
package com.example.myapplication.http;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* 作者:xuqing
* 时间:
* 邮箱:1693891473@qq.com
* 说明:post请求异步任务
*/
public class PostTask extends AsyncTask<Void, Void, String> {
private static final String TAG = "GetTask";
private HttpRequestCallBack listener;
private String url;
private Map<String, String> getmapparams;
private String type;
public PostTask(final String url, HttpRequestCallBack listener) {
this.url = url;
this.listener = listener;
}
public PostTask(final String url, final String type, final Map<String, String> getmapparams, HttpRequestCallBack listener) {
this.url = url;
this.listener = listener;
this.getmapparams=getmapparams;
this.type=type;
}
@SuppressLint("NewApi")
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
try {
String body="";
if(getmapparams!=null){
body= RequestUtil.clwuyGetPostBodyFormParameMap(getmapparams);
}
NetWorkRequest request = new NetWorkRequest();
Map<String, String> headerMap=new HashMap<>();
headerMap.put("x-method","post");
headerMap.put("x-request",type);
String contextType="application/json;charset=utf-8";
NetResponse response =request.qecrnNetWordRequst(url,"POST",contextType,body,headerMap);
Log.e(TAG, "doInBackground:response "+response.dkpdpResponseContent );
if(response.dkpdpResponseCode==200){
return response.dkpdpResponseContent;
}else{
return null;
}
} catch (Exception e) {
Log.e("kunge.hu", "GetTask Exception:" + e.toString());
}
return null;
}
@SuppressLint("NewApi")
@Override
protected void onPostExecute(String t) {
try {
if(!TextUtils.isEmpty(t)){
JSONObject jsonObject=new JSONObject(t);
listener.clwuyHttpCallBackListener(t);
}else{
Log.e(TAG, "onPostExecute: "+"网络服务器失败" );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
对外层调用方法
typescript
package com.example.myapplication.http;
import java.util.Map;
/**
* 作者:xuqing
* 时间:2023年11月28日10:17:12
* 邮箱:1693891473@qq.com
* 说明:对外层调用的方法
*/
public class NetCtrl {
public static void get(final String url, HttpRequestCallBack listener) {
new GetTask(url, listener).execute();
}
public static void get(final String url, final String type, final Map<String, String> params, HttpRequestCallBack listener) {
new GetTask( url,type, params, listener).execute();
}
public static void post(final String url, HttpRequestCallBack listener){
new PostTask( url, listener).execute();
}
public static void post(final String url, final String type,
final Map<String, String> params, HttpRequestCallBack listener){
new PostTask( url,type, params, listener).execute();
}
}
在MainActivity测试请求
get
typescript
//带请求参数
NetCtrl.get(url, "", null, new HttpRequestCallBack() {
@Override
public void clwuyHttpCallBackListener(String result) {
Log.e(TAG, "clwuyHttpCallBackListener: result-- >"+result );
}
@Override
public void clwuyHttpRequestFail(String errorString, int code) {
}
});
//不带请求参数
NetCtrl.get(url, new HttpRequestCallBack() {
@Override
public void clwuyHttpCallBackListener(String result) {
Log.e(TAG, "clwuyHttpCallBackListener: result-- >"+result );
}
@Override
public void clwuyHttpRequestFail(String errorString, int code) {
}
});
post
typescript
NetCtrl.post(url, "", null, new HttpRequestCallBack() {
@Override
public void clwuyHttpCallBackListener(String result) {
Log.e(TAG, "post clwuyHttpCallBackListener: result-- >"+result );
}
@Override
public void clwuyHttpRequestFail(String errorString, int code) {
}
});
NetCtrl.post(url, new HttpRequestCallBack() {
@Override
public void clwuyHttpCallBackListener(String result) {
Log.e(TAG, "clwuyHttpCallBackListener: "+"result -- > " +result );
}
@Override
public void clwuyHttpRequestFail(String errorString, int code) {
}
});