(一)、使用网络异步的方法:
调用代码:
new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... strings) { String httpUrl = strings[0]; return getHttpUrlConnection(httpUrl); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.e("tag", "responseJson :" + s); if (s == null) { return; } parserJson(s); } }.execute(mHttpUrl);
方法:
//加载网络路径 /** * 网络异步获取数据 * * @param httpUrl * @return */ public String getHttpUrlConnection(String httpUrl) { HttpURLConnection httpURLConnection = null; InputStream inputStream = null; try { URL url = new URL(httpUrl); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(500); httpURLConnection.setDoInput(true); if (httpURLConnection.getResponseCode() == 200) { Log.e("tag","123123"); inputStream = httpURLConnection.getInputStream(); String responseJson = readInPutStream(inputStream); Log.e("tag","123"+responseJson); return responseJson; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return null; } //读取流 public String readInPutStream(InputStream inputStream) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; StringBuilder stringBuilder = new StringBuilder(); try { while ((line = reader.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); }
(二)、使用第三方打包好的库:
需要下载两个库导入项目。
http://download.csdn.net/detail/zhangli_/9389498
http://download.csdn.net/detail/zhangli_/9389506
调用代码:
AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); asyncHttpClient.get(url, new TextHttpResponseHandler() { @Override public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, String s, Throwable throwable) { Log.e("tag", "onFailure AsysncHttpClicent :" + s); } @Override public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, String s) { Log.e("tag", "onSuccess AsysncHttpClicent :" + s); parserJson(s); } });