日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

centos模拟post请求_java模拟post和get请求(2019/10/25)

發布時間:2023/12/2 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 centos模拟post请求_java模拟post和get请求(2019/10/25) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、http含義的介紹
1.http協議是超文本傳輸協議--具體含義請百度
2.基于tcp/ip協議--注意和udp的區別
3.無狀態---本次請求記不住以往請求的狀態

4.無連接--每次連接只處理一個請求

5.媒體獨立

二、請求報文的組成部分

請求行 請求方式 請求url http協議版本

請求頭

關于請求頭和響應頭的信息可以參考以下信息

https://www.cnblogs.com/yumo1627129/p/7941220.html

請求體

post編碼方式

表格方式:application/x-www-form-urlencoded; charset=UTF-8

json格式:application/json

多媒體文件格式:multipart/form-data

三、java發送http請求(多種方式,目前只是用了一種方式,所以只記錄一種)

第一種:使用httpUrlConnection對象

知識: httpUrlConnection屬性 // 設置連接超時時間 connection.setConnectTimeOut(15000);// 設置讀取超時時間 connection.setReadTimeOut(15000);// 設置http的請求方式 connection.setRequestMethod("POST");// 設置http的header的信息,可參考《Java 核心技術 卷II》 connection.setRequestProperty("Connection", "Keep-Alive");// 設置是否向 httpUrlConnection 輸出, // 對于post請求,參數要放在 http 正文內,因此需要設為true。 // 默認情況下是false; connection.setDoOutput(true);// 設置是否從 httpUrlConnection 讀入,默認情況下是true; connection.setDoInput(true);

請求的步驟

//第一步--獲取httpUrlConnection的對象 //第二部--設置httpUrlConnection的屬性 //第三步--獲取讀出輸出流,寫入信息給服務器outputstream //第三步--獲取輸入流。獲取服務器的信息 inputstream

方式一:

1.get請求:

public static void testGetMethod(String httpUrl){URL url;HttpURLConnection conn = null;InputStream inputStream = null;try {1.創建對象url = new URL(httpUrl);conn = (HttpURLConnection) url.openConnection();2.設置參數conn.setDoInput(true);conn.setRequestMethod("GET");conn.setRequestProperty("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJOekU0WVdRd1pHRXRZVFZpWmkwME1tSmtMV0kzWXpRdE56STJPVEl6TWpjMFpqUTQifQ.MDnJHzEiLlNlwarfPeE8nExnGKfeNnSAprZcJdQMTBxrgePu1fe-0iE1ymn5hexs6xWRng1xJ9pP49QIlNZCIA");3.建立連接但是可以不顯示調用connection。int responseCode = conn.getResponseCode();System.out.println(responseCode);if (responseCode ==200){String str="";StringBuffer stringBuffer = new StringBuffer();4.讀取返回值inputStream = conn.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));while ((str =reader.readLine())!=null){stringBuffer.append(str);}//放到數組里System.out.println(stringBuffer);String[] split = Json.fromJsonAsArray(String.class,stringBuffer);System.out.println(split[0]);}} catch (Exception e) {e.printStackTrace();}finally {if (inputStream==null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (conn==null){conn.disconnect();}}}

2.post請求

表單類型:

public static void interfaceUntil(String path,String data){try {StringBuffer stringBuffer = new StringBuffer();1.創建對象URL url =new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();2.設置參數// 設置連接輸出流為true,默認false (post請求是以流的方式隱式的傳遞參數)conn.setDoOutput(true);// 設置連接輸入流為trueconn.setDoInput(true);// 設置請求方式為postconn.setRequestMethod("POST");// post請求緩存設為falseconn.setUseCaches(false); // // 設置該HttpURLConnection實例是否自動執行重定向 // conn.setInstanceFollowRedirects(true);// 設置內容的類型,設置為經過urlEncoded編碼過的from參數conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // conn.setRequestProperty("accept", "application/xml"); // conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36");conn.setRequestProperty("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJaVFl3WkdVeVpUSXRabU13WXkwME1URmhMV0ptTURRdE1EWXhPR1ptWWpZMlpHSXkifQ.q2Yqzu-ZoXTMm3ZjT1Q4j8feXO2GB13ziZiSHQAc1_eAfFdMMVMaWrFA2VtC17WfDFTnCU7iMtky1bVgw30fZQ");//urlConnection的輸入流 3.建立連接,可以不顯示調用connection方法 4.創建輸出函數,post請求體,字節流的形式OutputStream out = conn.getOutputStream();out.write(data.getBytes());out.flush(); 5.創建輸入流,讀取接口寫入的返回內容InputStream is = conn.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));String str = "";while ((str = br.readLine()) != null) {stringBuffer.append(str);}System.out.println(stringBuffer); // Pager pager = new Pager(); // System.out.println(pager); // System.out.println(pager.getPageSize()); // System.out.println(pager.getPage());Pager pager = Json.fromJson(Pager.class, stringBuffer);System.out.println(pager);//關閉流is.close();conn.disconnect();System.out.println("完整結束");} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {//合并告警idLong alertId =9626414696700001L;StringBuffer stringBuffer = new StringBuffer();stringBuffer.append("alertId=");stringBuffer.append(alertId);stringBuffer.append("&");stringBuffer.append("pager={page:");stringBuffer.append("1");stringBuffer.append(",pageSize:");stringBuffer.append("2");stringBuffer.append("}");注意:以下的形式是不可以采用的必須是上面的表單形式 // HashMap<String, Object> map = new HashMap<>(); // map.put("alertId",alertId); // Pager pager = new Pager(); // pager.setPage(1L); // pager.setPageSize(2L); // map.put("pager",pager); // System.out.println("傳遞的json數據:"+Json.toJson(map));interfaceUntil("http://192.168.101.244:16520/sap/alert/alertraw/pager",stringBuffer.toString());}

json類型:

public static void testPostJson(String path,String data){try {URL url = new URL(path);HttpURLConnection conn =(HttpURLConnection) url.openConnection();conn.setDoOutput(true);conn.setDoInput(true);conn.setRequestMethod("POST");conn.setUseCaches(false);conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");conn.setRequestProperty("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJNVFJtTmpreU5UVXROamd6TmkwMFpEVmtMV0V3TURNdE9UTTBOR1V5WWpCaU1XSXgifQ.pPvG67sbbZ-ZNVf8JAiHE6rzgb5nLPgCQgEOlMTYAx6eobB5tF3GnDHg6OwyYM4QPGPCSJ_0hZ0Qo1L1QbqtAQ");OutputStream os = conn.getOutputStream();os.write(data.getBytes());os.flush(); /* //讀取客戶端響應,變成string答應InputStream is = conn.getInputStream();InputStreamReader isr = new InputStreamReader(is);BufferedReader br = new BufferedReader(isr);int str;char buff[] = new char[1024];while ((str = isr.read(buff)) != -1) {System.out.println(buff);}*/is.close();os.close();conn.disconnect();System.out.println("完整結束");} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {/*形式:"id":9575280686300014;代碼:Map<String,String> dataMap = new HashMap<>();dataMap.put("id","9575280686300014");testPostJson("http://124.126.208.180:16520/sap/api/rest/alert/drill", Json.toJson(dataMap));*//* 形式{"pager":{"page":2,"pageSize":2}} */Pager pager = new Pager();pager.setPage(2L);pager.setPageSize(2L);testPostJson("http://124.126.208.180:16520/sap/api/rest/alert/getAlert",Json.toJson(pager));}

多媒體類型:

public static void postFile(String urlPath, File file, Map<String,Object> valueMap){HttpURLConnection conn;InputStream inputStream;OutputStream outputStream;final String newLine = "rn";final String boundaryPrefix = "--";try {String BOUNDARY="----------"+System.currentTimeMillis();//參數分割線StringBuffer divider = new StringBuffer();divider.append(boundaryPrefix).append(BOUNDARY).append(newLine);//結尾// 定義最后數據分隔線,即--加上BOUNDARY再加上--。StringBuffer end = new StringBuffer();end.append(newLine).append(boundaryPrefix).append(BOUNDARY).append(boundaryPrefix);URL url = new URL(urlPath);conn = (HttpURLConnection) url.openConnection();conn.setDoInput(true);conn.setDoOutput(true);conn.setUseCaches(false);conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+ BOUNDARY);String fileName = null;String fileValue = null;/*** 開始傳遞非文件參數* 參數分割符號-content內容-兩個空行-正文參數內容-結束標記*/StringBuffer stringBuffer = new StringBuffer();stringBuffer.append(divider);stringBuffer.append("Content-Disposition:form-data;name="fileId"");//兩個空行stringBuffer.append(newLine);stringBuffer.append(newLine);//參數stringBuffer.append("789");stringBuffer.append(end);System.out.println("非文件上傳參數"+stringBuffer);outputStream = conn.getOutputStream();outputStream.write(stringBuffer.toString().getBytes());/*開始文件上傳*/StringBuilder sb = new StringBuilder();sb.append(divider);// 文件參數,photo參數名可以隨意修改sb.append("Content-Disposition: form-data;name="file";filename="" + file.getName() + """);sb.append(newLine);sb.append(newLine);outputStream.write(sb.toString().getBytes());//開始輸出文件FileInputStream fileInputStream = new FileInputStream(file);byte[] bytes = new byte[1024];int length;while ((length=fileInputStream.read(bytes)) !=-1){outputStream.write(bytes);}//結束符號outputStream.write(end.toString().getBytes());outputStream.flush();//讀取響應inputStream = conn.getInputStream();BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));String str;if ((str = bufferedReader.readLine())!=null){System.out.println(str);}} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {File file = new File("D://wecenter//readme_first.html");HashMap<String, Object> map = new HashMap<>();map.put("fileId","123");System.out.println(file.exists());postFile("http://localhost:16520/test/upload",file,map);}

3.關于結果的處理

string類型: 使用reader讀出來的本來就是string類型

數組,list類型:

javabean對象:fastjson都可以這類的問題,目前使用的不是fastjson

三、胡思亂想記錄中

1.為什么不能直接使用objectOutputStream直接序列化輸出結果?

objectOutputstream需要寫入和寫出的版本號一致,這邊很明顯沒有版本號可以用。

2.fastjson的相關知識有待總結。

總結

以上是生活随笔為你收集整理的centos模拟post请求_java模拟post和get请求(2019/10/25)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。