1.HttpClient和httpurlconnection介绍
HttpClient是Apache开源组织提供的一个Http客户端,HttpClient封装了Session、Cookie等细节问题的处理。简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情 HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。由于HttpClient API较多,体型较大升级和维护起来较为繁琐,Android团队在API 23中移除了对HttpClient的支持。
2.HttpURLConnection是java的标准类,没有做封装,用起来比较原始
使用httpurlconnection实现get,post请求:
get请求传参:参数跟在url后
post请求传参:将参数放入输出流中
public static String httpUrlConnectionGet(参数) throws Throwable {
String result = null;
try {
trustAllHosts();
URL serverUrl = new URL(params);
HttpsURLConnection conn = (HttpsURLConnection) serverUrl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
conn.setConnectTimeout(connectTimeout);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (conn.getResponseCode() == 200) {
result = getReturn(conn);
} else {
logger.error("Return to Data is wrong");
}
logger.info("httpUrlConnectionget method end");
} catch (IOException e) {
logger.error(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
}
return result;
}
其中trustAllHosts();方法是跳过https证书,可以进行无证书访问
private static void trustAllHosts() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
} catch (Exception e) {
e.printStackTrace();
}
}
httpURLconnection post方法请求api
public static String httpUrlConnectionPost(String params, String requestUrl, String profilesActive) throws Throwable {
String result = null;
try {
if ("alpha".equals(profilesActive)) {
trustAllHosts();
}
URL serverUrl = new URL(requestUrl);
logger.info(serverUrl.toString());
logger.info("httpUrlConnectionPost method start");
HttpsURLConnection conn = (HttpsURLConnection) serverUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setConnectTimeout(connectTimeout);
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
logger.info(params);
out.writeBytes(params);
out.flush();
out.close();
if (conn.getResponseCode() == 200) {
result = getReturn(conn);
} else {
logger.error("Return to Data is wrong");
}
Integer code = conn.getResponseCode();
logger.info(code.toString());
result = getReturn(conn);
logger.info("httpUrlConnectionPost method end");
} catch (IOException e) {
logger.error(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
}
return result;
}
由于httpurlconnection是以输入输出流的形式进行数据传输,所以接到返回值需要转换成Sting字符串,使用obectMapper进行解析得到map,进而得到想要的数据。
public static String getReturn(HttpURLConnection connection) throws IOException {
StringBuffer buffer = new StringBuffer();
try (InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
String result = buffer.toString();
return result;
}
}
json解析:
public class JsonToMapUtil {
public static Map<String, Object> getMap(String result) throws Exception{
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> mapperMap = new HashMap<String, Object>();
Map<String, Object> data = mapper.readValue(result, mapperMap.getClass());
return data;
}
}
https证书:
http+ssl:证书一共分为两种,一种是域名申请证书,还有一种是IP申请证书
有一种情况是请求https的api,使用ip还是域名的url去申请是由证书属于哪种所决定的,如果是ip申请证书并且没有域名,那么就算是自己本地配置hosts域名,也是行不通的。但是大部分正式环境都是带有域名的
注意:
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
中的类型如果错误则会出现传参失败的情况。
小细节:
如果把此类定义为一个工具类,那么方法都要用static修饰
基础:每个线程都有自己的线程栈,栈与线程同时创建,每一个虚拟机线程都有自己的程序计数器PC,在任何时刻,一个虚拟机线程只会执行一个方法的代码,这个方法称为该线程的当前方法,如果这个方法不是native的,程序计数器就保存虚拟机正在执行的字节码指令的地址。线程调用方法的时候会创建栈帧,用于保存局部变量表和操作数栈以及指向该类常量池的引用
静态方法虽然是同一个方法,但是不同线程在调用,程序计数器的值是不一样的,操作这两个线程不会相互影响(假设不存在访问共享变量的情况)
1.保证不依靠其他类、属性、方法等
2.不需要考虑方法同步
3. 如果使用单例类,需要考虑线程同步的情况,这是工具类不使用单例的原因
这里还有一点需要补充:在写工具类时,最好是将其构造方法私有化,避免意外的初始化类,做无意义的工作
其中单例和多例概念:
https://blog.youkuaiyun.com/u013126379/article/details/51885929
这篇文章介绍的很清晰