使用HttpURLConnection+AsyncTask访问webservice接口(返回json字符串)

it2022-05-05  128

现在很多APP程序网络通信都是基于http的,数据格式我访问常常使用如下配置,

DEMO下载地址:http://www.eoeandroid.com/thread-589937-1-1.html

截图:

                

 

 

 

 

 

 

 

 

关键代码如下:

1.CstorAsyncTask.java[异步操作]

public class CstorAsyncTask extends AsyncTask<Object, Integer, String> { /** * 回调接口 */ private RequestCallBack callback;

public CstorAsyncTask(RequestCallBack cb) { this.callback = cb; }

@SuppressWarnings("unchecked") @Override protected String doInBackground(Object... params) { String responseStr = ""; String requestMethod = params[0].toString(); String url = params[1].toString(); HashMap<String, String> param = (HashMap<String, String>) params[2]; if (requestMethod.equals(HttpTools.POST)) { responseStr = HttpURLConnectionTools.obtainPostUrlContext(url, param); } else if (requestMethod.equals(HttpTools.GET)) { responseStr = HttpURLConnectionTools .obtainGetUrlContext(url, param); } return responseStr; }

@Override protected void onPostExecute(String result) { super.onPostExecute(result); if (null != callback) { if (httpIsNull(result)) { callback.onFailure(); } else { callback.onSuccess(result); } } } public static boolean httpIsNull(String str) { if (null == str) { return true; } if (("").equals(str)) { return true; } if (("null").equals(str)) { return true; } return false; }}

 

2.RequestCallBack.java[数据加载回调接口]

public interface RequestCallBack { public void onSuccess(String response);

public void onFailure();}

3.HttpURLConnectionTools.java[HTTP请求(GET,POST)]

public class HttpURLConnectionTools { /** * 通过GET获取某个url的内容 * * @param strUrl * @param params * @return String */ public static String obtainGetUrlContext(String strUrl, Map<String, String> params) { String responseStr = ""; InputStream is = null; HttpURLConnection conn = null; BufferedReader bufferedReader = null; try { Log.e(HttpTools.TAG, getRequestUrl(strUrl, params)); URL url = new URL(getRequestUrl(strUrl, params)); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(HttpTools.ReadOutTime /* milliseconds */); conn.setConnectTimeout(HttpTools.ConnectOutTime /* milliseconds */); conn.setRequestMethod(HttpTools.GET); conn.setDoInput(true); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { // is = conn.getInputStream(); // responseStr = readInputStream(is); bufferedReader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { responseStr += line; } } } catch (Exception e) { Log.e(HttpTools.TAG, "obtainGetUrlContext is err"); // e.printStackTrace(); } finally { if (is != null) { try { conn.disconnect(); is.close(); } catch (IOException e) { e.printStackTrace(); } } } return responseStr; }

/** * 通过POST获取某个url的内容 * * @param strUrl * @param params * @return String */ public static String obtainPostUrlContext(String strUrl, Map<String, String> params) { String responseStr = ""; PrintWriter printWriter = null; HttpURLConnection conn = null; BufferedReader bufferedReader = null; try { URL url = new URL(strUrl); // 打开和URL之间的连接 conn = (HttpURLConnection) url.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Content-Length", String.valueOf(PostRequestUrl(params).length())); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(10000 /* milliseconds */); conn.setRequestMethod("POST"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 printWriter = new PrintWriter(conn.getOutputStream()); // 发送请求参数 printWriter.write(PostRequestUrl(params).toString()); // flush输出流的缓冲 printWriter.flush(); // 根据ResponseCode判断连接是否成功 int responseCode = conn.getResponseCode(); if (responseCode != 200) { Log.e(HttpTools.TAG, "data is err"); } else { // responseStr = readInputStream(conn // .getInputStream()); bufferedReader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { responseStr += line; } } } catch (Exception e) { Log.e(HttpTools.TAG, "obtainPostUrlContext is err"); e.printStackTrace(); } finally { conn.disconnect(); if (printWriter != null) { printWriter.close(); } } return responseStr; }

/** * 拼装get访问URL * * @param strUrl * @param params * @return * @throws UnsupportedEncodingException */ private static String getRequestUrl(String strUrl, Map<String, String> params) { String requestUrl = strUrl; int i = 0; for (Map.Entry<String, String> param : params.entrySet()) { if (i == 0) { requestUrl += "?"; } else { requestUrl += "&"; } try { if ((null == param.getValue()) || "".equals(param.getValue())) { requestUrl += param.getKey() + "="; } else { requestUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8"); // +param.getValue(); } } catch (Exception e) { Log.e(HttpTools.TAG, "getRequestUrl第" + i + "个数据 is err"); // e.printStackTrace(); } i++; } return requestUrl; }

/** * 拼装POST访问URL * * @param params * @return * @throws UnsupportedEncodingException */ @SuppressWarnings("rawtypes") private static StringBuffer PostRequestUrl(Map<String, String> params) { StringBuffer buffers = new StringBuffer(); Iterator<Entry<String, String>> it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry element = (Map.Entry) it.next(); buffers.append(element.getKey()); buffers.append("="); buffers.append(element.getValue()); buffers.append("&"); } if (buffers.length() > 0) { buffers.deleteCharAt(buffers.length() - 1); } return buffers; }}

4.HttpTools.java[网络请求常量]

public class HttpTools { // log标识 public static final String TAG = "HttpTools"; // 请求类型 public static final String GET = "GET"; public static final String POST = "POST"; // 读取超时 public static final int ReadOutTime = 100000; // 连接超时 public static final int ConnectOutTime = 100000;}

 

DEMO下载地址:http://www.eoeandroid.com/thread-589937-1-1.html

转载于:https://www.cnblogs.com/androidDR/p/4545793.html

相关资源:AsyncTask HttpURLConnection

最新回复(0)