Android HttpsURLConnection get、post 访问网络
来源:互联网 发布:李霖丰淘宝店不做了吗 编辑:程序博客网 时间:2024/06/04 22:35
证书验证类,此处默认通过所有证书HttpUtils 类public class HttpUtils { public static void trustAllHosts() { final String TAG = "trustAllHosts"; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { LogF.i(TAG, "checkClientTrusted"); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { LogF.i(TAG, "checkServerTrusted"); } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } }}final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; }};1、get 请求/** * get方式请求服务器 * * @param param 请求时包含的参数 * @return */ public static String get(RequestParam param) throws IOException, ServerException { String urlString = param.getUrl(); if (TextUtils.isEmpty(urlString)) return null;HttpURLConnection httpURLConnection = null;HttpsURLConnection https = null;BufferedReader bufferedReader = null; try {URL url = new URL(urlString);HttpUtils.trustAllHosts();// 打开连接if (url.getProtocol().toLowerCase().equals("https")) {https = (HttpsURLConnection) url.openConnection();https.setHostnameVerifier(DO_NOT_VERIFY);httpURLConnection = https;} else {httpURLConnection = (HttpURLConnection) url.openConnection();}//设置读取超时//设置连接超时 httpURLConnection.setReadTimeout(10 * 1000); httpURLConnection.setConnectTimeout(5 * 1000); // Set the post method. Default is GET httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); if (httpURLConnection.getResponseCode() == 200) { bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String lineStr = ""; while ((lineStr = bufferedReader.readLine()) != null) { stringBuffer.append(lineStr + "\n"); } return stringBuffer.toString(); } else { Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode()); throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode()); } } finally { if(bufferedReader != null) bufferedReader.close(); if(httpURLConnection != null)httpURLConnection.disconnect();if(https != null)https.disconnect();}}2、post 请求
/** * post 方式请求服务器 * * @param param 请求参数 * @return 响应 json 串 * @throws IOException 文本异常,超时等 */ public static String post(RequestParam param) throws IOException, ServerException { String urlString = param.getUrl(); if (TextUtils.isEmpty(urlString)) return null;HttpURLConnection httpURLConnection = null;HttpsURLConnection https = null;OutputStreamWriter outputStreamWriter = null; BufferedReader bufferedReader = null; try { //url URL url = new URL(urlString);HttpUtils.trustAllHosts();// 打开连接if (url.getProtocol().toLowerCase().equals("https")) {https = (HttpsURLConnection) url.openConnection();https.setHostnameVerifier(DO_NOT_VERIFY);httpURLConnection = https;} else {httpURLConnection = (HttpURLConnection) url.openConnection();}//设置读取超时 //设置连接超时 httpURLConnection.setReadTimeout(10 * 1000); httpURLConnection.setConnectTimeout(5 * 1000); // Read from the connection. Default is true. httpURLConnection.setDoInput(true); // Output to the connection. Default is // false, set to true because post // method must write something to the // connection // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true httpURLConnection.setDoOutput(true); // Post cannot use caches // Post 请求不能使用缓存 httpURLConnection.setUseCaches(false); // Set the post method. Default is GET httpURLConnection.setRequestMethod("POST"); // This method takes effects to // every instances of this class. // URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。 // connection.setFollowRedirects(true); // This methods only // takes effacts to this // instance. // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数 httpURLConnection.setInstanceFollowRedirects(true); // Set the content type to urlencoded, // because we will write // some URL-encoded content to the // connection. Settings above must be set before connect! // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode // 进行编码 httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 httpURLConnection.connect();// DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());// dataOutputStream.writeBytes(param.getParams());// dataOutputStream.flush();// dataOutputStream.close(); // flush and close// outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"); outputStreamWriter.write(param.getParams()); outputStreamWriter.flush(); if (httpURLConnection.getResponseCode() == 200) { bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String lineStr = ""; while ((lineStr = bufferedReader.readLine()) != null) { stringBuffer.append(lineStr + "\n"); } return stringBuffer.toString(); } else { Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode()); throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode()); } } finally { if(bufferedReader != null) bufferedReader.close(); if(outputStreamWriter != null) outputStreamWriter.close(); if(httpURLConnection != null)httpURLConnection.disconnect();if(https != null)https.disconnect();}}RequestParam类
/*** 描述:网络 请求参数 * @author HJK */public class RequestParam { private String url; private Map<String, Object> params; public void put(String key, String value) { if (params == null) params = new HashMap<String, Object>();params.put(key, value);} public String getUrl() { return url;} public void setUrl(String url) { this.url = url;} public List<NameValuePair> postParams() { if (params == null) return null;List<NameValuePair> param = new ArrayList<NameValuePair>(); for (String key:params.keySet()) param.add(new BasicNameValuePair(key, params.get(key)+"")); return param;} public String getParams() { if (params == null) return null;StringBuffer stringBuffer = new StringBuffer(); for (String key : params.keySet()) { stringBuffer.append(key).append("=").append(params.get(key)).append("&");} if(stringBuffer.length()>0) stringBuffer.deleteCharAt(stringBuffer.length()-1); return stringBuffer.toString();} public String toString() { return params == null?null:params.toString();}}ServerException类
/**
* 描述:服务器异常
* @author HJK
*/
public class ServerException extends Exception {
public ServerException() {
super();
}
public ServerException(String msg) {
super(msg);
}
public ServerException(String msg, Throwable cause) {
super(msg, cause);
}
public ServerException(Throwable cause) {
super(cause);
}}
0 0
- Android HttpsURLConnection get、post 访问网络
- Android HttpURLConnection get、post 访问网络
- Android HttpClient get、post 访问网络
- Android之HttpsURLConnection访问网络(android https协议)
- android 使用http get 与post 访问网络
- Android下get/post访问网络及webService的调用
- Android 通过get和post方法访问网络
- HttpsURLConnection实现SSL的GET/POST请求
- HttpsURLConnection实现SSL的GET/POST请求
- Http访问网络之GET和POST
- android开发 使用HttpClient访问网络,post、get方式。注册、登陆、上传文件。
- Android中使用HttpURLConnection和HttpClient实现GET和POST请求访问网络
- android中HTTP协议访问网络及其方式及其http的GET和POST的优缺点
- 安卓网络--网络访问Post和Get
- Android利用Get、Post 获取网络数据
- Android网络交互Get,POST简介
- Android-封装post和get 网络请求
- android 基础 网络交互 get/post
- jstack分析死锁
- 模拟登录
- 网络编程
- 1537: [POI2005]Aut- The Bus 线段树优化DP
- 实验8-2-3 删除字符 (20分)
- Android HttpsURLConnection get、post 访问网络
- [Django]SE项目回忆录(一)
- Android studio "社会化分享"实现步骤(总结mob网步骤)
- aix中的makefie不支持ifeq
- ansible安装测试
- 获取指定格式的当前时间字符串
- 写在Plist 里的授权
- DES加密
- UE4中 指定蓝图GameMode的父类为C++生成的GameMode方法