网络请求工具类HttpUtil
来源:互联网 发布:软件开发工程师 编辑:程序博客网 时间:2024/06/05 22:59
import android.content.Context;import android.os.AsyncTask;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import myapplication.myapplication.jiekou.HttpCallBack;/** * Created by Administrator on 2017/10/18. */public class HttpUtil { public static void requestDataByHttp(final String path, Context context, final HttpCallBack callBack){ new AsyncTask<Void, Void, String>(){ @Override protected String doInBackground(Void... voids) { try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int responseCode = connection.getResponseCode(); if(responseCode == 200){ InputStream inputStream = connection.getInputStream(); String s = streamToString(inputStream, "utf-8"); return s; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); callBack.onRequestComplete(s); } }.execute(); } private static String streamToString(InputStream inputStream,String charset) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String s = null; StringBuilder builder = new StringBuilder(); while ((s = bufferedReader.readLine()) != null){ builder.append(s); } bufferedReader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }}
接口:
/** * Created by Administrator on 2017/10/18. */public interface HttpCallBack { void onRequestComplete(String json);}
阅读全文
0 0
- HttpUtil---网络请求工具类
- 网络请求工具类HttpUtil
- 网络请求应该是HttpUtil 工具类
- Android网络请求HttpUtil封装工具类
- Http请求工具类 httputil
- Http请求工具类HttpUtil
- HttpUtil工具类发送post请求
- httputil用http获取请求的工具类
- HttpUtil工具类
- httpUtil工具类
- HttpUtil 工具类
- HttpUtil工具类
- HttpUtil工具类
- Android自定义的网络连接工具类HttpUtil
- Android工具类系列-HttpUtil
- HttpUtil工具
- 网络请求工具类
- 网络请求工具类
- adb shell input: keyevent,tap,swipe
- HDU-1280 前m大的数
- 缓动函数速查表
- 锚文本链接是什么?
- 详解spl_autoload_register()函数
- 网络请求工具类HttpUtil
- 工具类 把一个字节流转成字符串
- Linux SVN 启动
- 「网络流 24 题」餐巾计划
- leetcode--Search a 2D Matrix
- 【队内胡策】2017.10.16
- centos7下使用yum安装mysql5.7.10
- js获取地址栏参数的值
- Jquery validate验证表单时多个name相同的元素