Android 原生HttpURLConnection网络请求工具类(get post)
2017-09-02 16:50
761 查看
public class NetworkUtil { /* * 传入一个Url地址 返回一个JSON字符串 * 网络请求的情况分析: * 如果是404 500 ... 代表网络(Http协议)请求失败 * 200 服务器返回成功 * 业务成功 /业务失败 * */ public static String doGet(String urlPath) { try { URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); return reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } return "{ \"success\": false,\n \"errorMsg\": \"后台服务器开小差了!\",\n \"result\":{}}"; } /* * 传入一个Url地址 返回一个JSON字符串 * */ public static String doPost(String urlPath, HashMap<String, String> paramsMap) { try { URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); //-------------------------------- conn.setDoOutput(true); conn.getOutputStream().write(getParams(paramsMap).getBytes()); //-------------------------------- if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); return reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } return "{ \"success\": false,\n \"errorMsg\": \"后台服务器开小差了!\",\n \"result\":{}}"; } private static String getParams(HashMap<String, String> paramsMap) { String result = ""; for (HashMap.Entry<String, String> entity : paramsMap.entrySet()) { result += "&" + entity.getKey() + "=" + entity.getValue(); } return result.substring(1); } }
相关文章推荐
- 第十二篇:Android GET请求获取网络数据以及POST数据(使用HttpURLConnection)
- Android网络请求,Get方式请求,HttpURLConnection请求工具类
- Android中使用HttpURLConnection和HttpClient实现GET和POST请求访问网络
- Android-----------HttpURLConnection的 get 请求和 post 请求 (可以下载浏览的内容)
- Android用httpURLConnection发送post网络请求并拿到数据
- Android_HttpURLConnection_Get和Post请求
- HttpUrlConnection和HttpClient和android-async-http框架的GET和POST请求
- android 中访问网络介绍 一 (基于httpurlconnection 的中get请求)
- Android网络通信技术之基于HttpURLConnection的POST/GET传值问题
- Http学习之使用HttpURLConnection发送post和get请求 android
- 【Android学习】网络通信----以HttpURLConnection Post请求为例
- Android-----HttpURLConnection的 get 请求和 post 请求
- HttpURLConnection,get,post,网络请求
- HttpURLConnection:POST和GET 网络请求
- Android之HttpURLConnection的GET和POST请求
- Android开发之网络通信(HttpURLConnection,HttpClient,HttpGet,HttpPost)
- Android HttpURLConnection(Get,Post方式)进行网络通信 获取数据和网络图片
- (转)Android_HttpURLConnection_Get和Post请求
- Android HttpURLConnection get、post 访问网络
- Android_HttpURLConnection_Get和Post请求