HttpUtils
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<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String post(String url, Map<String, String> header, Map<String, String> param, StringEntity entity)
throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
if (MapUtils.isNotEmpty(param)) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> 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() {
String url = "http://192.168.1.180:4050";
try {
String responseContent = postXML(url, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<Transfer attribute=\"Connect\">\n" +
"<ext id=\"20013\"/>\n" +
"<outer to=\"15505510628\"/>\n" +
"</Transfer>");
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("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<Transfer attribute=\"Connect\">\n" +
"<ext id=\"20013\"/>\n" +
"<outer to=\"15505510628\"/>\n" +
"</Transfer>", "UTF-8");
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();
}
}
}
複製程式碼