本文共 10340 字,大约阅读时间需要 34 分钟。
- HttpUtils
/** * * @ClassName: HttpsUtils * @Description: TODO(https post忽略证书请求) */public class HttpClientUtils { private static final String HTTP = "http"; private static final String HTTPS = "https"; private static SSLConnectionSocketFactory sslsf = null; private static PoolingHttpClientConnectionManager cm = null; private static SSLContextBuilder builder = null; static { try { builder = new SSLContextBuilder(); // 全部信任 不做身份鉴定 builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{ "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE); Registry registry = RegistryBuilder. create() .register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build(); cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(200);// max connection } catch (Exception e) { e.printStackTrace(); } } /** * httpClient post请求 * * @param url 请求url * @param header 头部信息 * @param param 请求参数 form提交适用 * @param entity 请求实体 json/xml提交适用 * @return 可能为空 需要处理 * @throws Exception */ public static String post(String url, Map header, Map param, StringEntity entity) throws Exception { String result = ""; CloseableHttpClient httpClient = null; try { httpClient = getHttpClient(); //HttpGet httpPost = new HttpGet(url);//get请求 HttpPost httpPost = new HttpPost(url);//Post请求 // 设置头信息 if (MapUtils.isNotEmpty(header)) { for (Map.Entry entry : header.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } // 设置请求参数 if (MapUtils.isNotEmpty(param)) { List formparams = new ArrayList (); for (Map.Entry entry : param.entrySet()) { // 给参数赋值 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); httpPost.setEntity(urlEncodedFormEntity); } // 设置实体 优先级高 if (entity != null) { httpPost.addHeader("Content-Type", "text/xml"); httpPost.setEntity(entity); } HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); System.out.println("状态码:" + statusCode); if (statusCode == HttpStatus.SC_OK) { HttpEntity resEntity = httpResponse.getEntity(); result = EntityUtils.toString(resEntity); } else { readHttpResponse(httpResponse); } } catch (Exception e) { throw e; } finally { if (httpClient != null) { httpClient.close(); } } return result; } public static String postXML(String url,String xml){ CloseableHttpClient client = null; CloseableHttpResponse resp = null; try{ HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8"); client = HttpClients.createDefault(); StringEntity entityParams = new StringEntity(xml,"utf-8"); httpPost.setEntity(entityParams); client = HttpClients.createDefault(); resp = client.execute(httpPost); String resultMsg = EntityUtils.toString(resp.getEntity(),"utf-8"); return resultMsg; }catch (Exception e){ e.printStackTrace(); }finally { try { if(client!=null){ client.close(); } if(resp != null){ resp.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } public static CloseableHttpClient getHttpClient() throws Exception { CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm) .setConnectionManagerShared(true).build(); return httpClient; } public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException { StringBuilder builder = new StringBuilder(); // 获取响应消息实体 HttpEntity entity = httpResponse.getEntity(); // 响应状态 builder.append("status:" + httpResponse.getStatusLine()); builder.append("headers:"); HeaderIterator iterator = httpResponse.headerIterator(); while (iterator.hasNext()) { builder.append("\t" + iterator.next()); } // 判断响应实体是否为空 if (entity != null) { String responseString = EntityUtils.toString(entity); builder.append("response length:" + responseString.length()); builder.append("response content:" + responseString.replace("\r\n", "")); } return builder.toString(); } @Test public void testSendHttpPost3() { //https://209.160.54.4/suns/XML_Rx.php String url = "http://192.168.1.180:4050"; try { String responseContent = postXML(url, " \n" + " \n" + " \n" + " \n" + " "); System.out.println(responseContent); } catch (Exception e) { e.printStackTrace(); } } @Test public void testSendHttpPost2() { String url = "http://192.168.1.180:4050"; try { StringEntity entity = new StringEntity(" \n" + " \n" + " \n" + " \n" + " ", "UTF-8"); // 不指定参数名的方式来POST数据 String responseContent = post(url, null, null, entity); System.out.println(responseContent); } catch (Exception e) { e.printStackTrace(); } } }复制代码
- io的简单操作
/** * @Author : leisure * @Date : 2019/1/24 */@RunWith(SpringRunner.class)public class IOTest { @Test public void fileTest() { File file = new File("D:/file-io"); try { if (file.exists()) { System.out.println("文件名称:" + file.getName()); System.out.println("文件路径:" + file.getAbsolutePath());// File[] files = file.listFiles();// System.out.println("文件数目:" + files.length);// for (File file1 : files) {// System.out.println(file.getName());// } System.out.println(file.canRead()); System.out.println(file.canWrite()); } } catch (Exception e) { e.printStackTrace(); } } /** * file stream */ @Test public void fileStream() { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("D:/file-io/io.txt"); fos = new FileOutputStream("D:/file-io/io-out.txt"); byte[] bytes = new byte[512]; int hasRead = 0; while ((hasRead = fis.read(bytes, 0, bytes.length)) != -1) { //每读取一次就写一次,读多少就写多少 fos.write(bytes, 0, hasRead); } } catch (Exception e) { e.printStackTrace(); } /** * jdk1.7 在try中会自动关闭流 */// finally {// if (fis != null){// try {// fis.close();// }catch (IOException e){// e.printStackTrace();// }// }// if (fos != null){// try {// fos.close();// }catch (IOException e){// e.printStackTrace();// }// }// } } /** * char stream */ @Test public void charStream() { FileWriter fw = null; FileReader fr = null; try { fr = new FileReader("D:/file-io/io.txt"); fw = new FileWriter("D:/file-io/io-reader.txt"); char[] chars = new char[64]; // 每个char都占两个字节,每个字符或者汉字都是占2个字节,因此无论buf长度为多少,总是能读取中文字符长度的整数倍,不会乱码 int flag = 0; while ((flag = fr.read(chars, 0, chars.length)) != -1) { // 如果buf的长度大于文件每行的长度,就可以完整输出每行,否则会断行。 // 循环次数 = 文件字符数 除以 buf长度 fw.write(chars, 0, flag);//写入文件 } //如果忘记关闭文件(close)同时也没有调用flush(),则被写入的文件中是没有内容的。在关闭文件的同时系统会自动调用flush()。 //fw.flush(); fw.close();//关闭流 } catch (IOException e) { e.printStackTrace(); }finally { try { if (fr != null) fr.close(); if (fw != null) fw.close(); }catch (IOException e){ e.printStackTrace(); } } } /** * char buffer strearm */ @Test public void charBufferSteam() { BufferedWriter bw = null; BufferedReader br = null; StringBuilder sb = null; try { FileReader fr = new FileReader("D:/file-io/io.txt"); FileWriter fw = new FileWriter("D:/file-io/io-buffer.txt"); BufferedWriter bw = new BufferedWriter(fw); br = new BufferedReader(fr); sb = new StringBuilder(); while (br.readLine() != null){ sb.append(br.readLine()).append("\r\n"); } bw.write(sb.toString(),0,sb.toString().length()); //如果忘记关闭文件(close)同时也没有调用flush(),则被写入的文件中是没有内容的。在关闭文件的同时系统会自动调用flush()。 br.close(); bw.close(); }catch (IOException e){ e.printStackTrace(); }finally { try { if (br != null) br.close(); if (bw != null) bw.close(); }catch (IOException e){ e.printStackTrace(); } } } /** * 中文占两个字节会有中文乱码 */ @Test public void bufferStream(){ FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("D:/file-io/io.txt"); fos = new FileOutputStream("D:/file-io/io-buffer-stream.txt"); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] bytes = new byte[1024]; int flag = 0; while ((flag = bis.read(bytes,0,bytes.length)) != -1){ bos.write(bytes,0,flag); //如果忘记关闭文件(close)同时也没有调用flush(),则被写入的文件中是没有内容的。在关闭文件的同时系统会自动调用flush()。 bos.flush();// bos.close(); 不需要关闭out流// bis.close(); } }catch (IOException e){ e.printStackTrace(); } }}复制代码
转载地址:http://fnrma.baihongyu.com/