java 編寫http連接,以httpclient 方式。
第一步是需要導入包:
主要有以上幾個包。
第二步:編寫代碼如下:
package test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.*; public class B { public void basic_conf(HttpPost httpPost,HashMap<String, String> headers){ //為post 生成默認的請求頭參數,但是傳遞的參數是:map視圖格式 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); httpPost.setHeader("Proxy-Connection", "keep-alive"); httpPost.setHeader("Accept", "application/json, text/javascript, */*"); //httpPost.setHeader("Accept-Encoding","gzip, deflate"); if (headers != null) { for (String key : headers.keySet()) { httpPost.setHeader(key, headers.get(key)); } } } public void basic_conf(HttpGet httpGet,HashMap<String, String> headers){ //為get請求傳遞默認的請求頭參數 httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); httpGet.setHeader("Proxy-Connection", "keep-alive"); httpGet.setHeader("Accept", "application/json, text/javascript, */*"); //httpPost.setHeader("Accept-Encoding","gzip, deflate"); if (headers != null) { for (String key : headers.keySet()) { httpGet.setHeader(key, headers.get(key)); } } } public String content_type(String s){ //為了判斷返回的響應頭,contentType是否包含了別的編碼要求 String result=null; if(s.toLowerCase().contains("gbk")){ result="GBK"; }else if(s.toLowerCase().contains("utf-8")){ result="UTF-8"; }else if(s.toLowerCase().contains("gb2312")){ result="GB2312"; }else if(s.toLowerCase().contains("iso-8859-1")){ result="ISO-8859-1"; } return result; } public String post(String url, HashMap<String, String> headers,String param) throws Exception { HttpPost httpPost = new HttpPost(url); basic_conf(httpPost,headers); StringEntity entity = new StringEntity(param); httpPost.setEntity(entity); HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost); //發送請求 int statusCode; statusCode = httpResponse.getStatusLine().getStatusCode(); //獲取響應碼 if (statusCode == 200) { //判斷請求是不是200 HttpEntity res=httpResponse.getEntity(); String con_type=res.getContentType().getValue(); //獲取響應報文頭的編碼格式 ByteArrayOutputStream out = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(out); //將獲取的報文寫入數組流中 Header gce=res.getContentEncoding(); //報文是否進行了壓縮 if(gce!=null){ //判斷是不是壓縮了的 if(gce.getValue().toLowerCase().contains("gzip")) { ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); //將響應報文寫入輸出流 try { GZIPInputStream ungzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = ungzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } catch (Exception e) { e.printStackTrace(); } } }else{ //如果不需要壓縮,直接將字節流轉成字節數組,然后由字節數組根據一定的編碼格式,最后生成字符串 String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } } return "響應碼為:"+statusCode; } public String post(String url,String param) throws Exception { HttpPost httpPost = new HttpPost(url); basic_conf(httpPost,null); StringEntity entity = new StringEntity(param); httpPost.setEntity(entity); HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost); int statusCode; statusCode = httpResponse.getStatusLine().getStatusCode(); if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判斷請求是不是200 HttpEntity res=httpResponse.getEntity(); String con_type=res.getContentType().getValue(); //獲取響應報文頭的編碼格式 ByteArrayOutputStream out = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(out); //將獲取的報文寫入數組流中 Header gce=res.getContentEncoding(); //報文是否進行了壓縮 if(gce!=null){ //判斷是不是壓縮了的 if(gce.getValue().toLowerCase().contains("gzip")) { ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); //將響應報文寫入輸出流 try { GZIPInputStream ungzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = ungzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } catch (Exception e) { e.printStackTrace(); } } }else{ String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } } return "響應碼為:"+statusCode; } public String get(String url, HashMap<String, String> headers) throws Exception { HttpGet httpGet = new HttpGet(url); basic_conf(httpGet,headers); HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet); int statusCode; statusCode = httpResponse.getStatusLine().getStatusCode(); if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判斷請求是不是200 HttpEntity res=httpResponse.getEntity(); String con_type=res.getContentType().getValue(); //獲取響應報文頭的編碼格式 ByteArrayOutputStream out = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(out); //將獲取的報文寫入數組流中 Header gce=res.getContentEncoding(); //報文是否進行了壓縮 if(gce!=null){ //判斷是不是壓縮了的 if(gce.getValue().toLowerCase().contains("gzip")) { ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); //將響應報文寫入輸出流 try { GZIPInputStream ungzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = ungzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } catch (Exception e) { e.printStackTrace(); } } }else{ String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } } return "響應碼為:"+statusCode; } public String get(String url) throws Exception { HttpGet httpGet = new HttpGet(url); basic_conf(httpGet,null); HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet); int statusCode; statusCode = httpResponse.getStatusLine().getStatusCode(); if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判斷請求是不是200 HttpEntity res=httpResponse.getEntity(); String con_type=res.getContentType().getValue(); //獲取響應報文頭的編碼格式 ByteArrayOutputStream out = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(out); //將獲取的報文寫入數組流中 Header gce=res.getContentEncoding(); //報文是否進行了壓縮 if(gce!=null){ //判斷是不是壓縮了的 if(gce.getValue().toLowerCase().contains("gzip")) { ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); //將響應報文寫入輸出流 try { GZIPInputStream ungzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = ungzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } catch (Exception e) { e.printStackTrace(); } } }else{ String gbkstr= new String(out.toByteArray(), content_type(con_type)); return gbkstr; } } return "響應碼為:"+statusCode; } /** * @param args */ public static void main(String[] args) { System.setProperty("http.proxyHost", "127.0.0.1"); System.setProperty("https.proxyHost", "127.0.0.1"); System.setProperty("http.proxyPort", "8889"); System.setProperty("https.proxyPort", "8889"); // TODO Auto-generated method stub B x=new B(); HashMap<String, String> map=new HashMap<String, String>(); map.put("Cookie","cod=3000.50000; JSESSIONID=B612C9CF4BE6E10A220EDE8E91D754B4; csd=50008"); //為了請求頭傳遞參數 map.put("Content-Type","multipart/form-data; boundary=----WebKitFormBoundaryx43rZoh62YQipnV1"); map.put("Upgrade-Insecure-Requests","1"); map.put("Cache-Control","max-age=0"); String j="platform_code=&charge_status=&mian_body=&charge_channel_code=&push_flag=&send_flag=&update_flag=&operate_name=&createTimeStart=2018-11-23&createTimeEnd=2018-11-30&updateTimeStart=&updateTimeEnd=&charge_type=1&single_no=&id_card=&bank_no=&loan_no=¤tPage=1&limit=10";try { String xx=x.post("http://sit1-credit.zhph.lan/p2pPaymentAppointmentAction.do",map,j); System.out.println(xx); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
下面對一種特殊的傳遞格式進行講解一下:
加入我將要傳遞的是一個文件,或者說,請求是以:multipart/form-data 方式。我們對請求報文的編寫格式必須如下面的param變量。針對這種請求體,建議直接使用jmeter,來的更容易。當然測試時還有一種方式:跳過這個步驟。
public static void main(String[] args) { System.setProperty("http.proxyHost", "127.0.0.1"); //這個是為了將http請求通過fiddler進行監控起來 System.setProperty("https.proxyHost", "127.0.0.1"); System.setProperty("http.proxyPort", "8889"); System.setProperty("https.proxyPort", "8889"); // TODO Auto-generated method stub B x=new B(); HashMap<String, String> map=new HashMap<String, String>(); map.put("Cookie","cod=3000.50000; JSESSIONID=B612C9CF4BE6E10A220EDE8E91D754B4; csd=50008"); map.put("Content-Type","multipart/form-data; boundary=----WebKitFormBoundaryx43rZoh62YQipnV1"); map.put("Upgrade-Insecure-Requests","1"); map.put("Cache-Control","max-age=0"); //String j="platform_code=&charge_status=&mian_body=&charge_channel_code=&push_flag=&send_flag=&update_flag=&operate_name=&createTimeStart=2018-11-23&createTimeEnd=2018-11-30&updateTimeStart=&updateTimeEnd=&charge_type=1&single_no=&id_card=&bank_no=&loan_no=¤tPage=1&limit=10"; String param="------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"org.apache.struts.taglib.html.TOKEN\""+"\r\n" +"\r\n" +"f996182ad68010c19ca47b58e09ec60e"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"org.apache.struts.taglib.html.TOKEN\""+"\r\n" +"\r\n" +"f996182ad68010c19ca47b58e09ec60e"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"loanContractNo\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"loanName\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"mainBody\""+"\r\n" +"\r\n" +"ZH"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"areaNo\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"signAreaNo\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"v\n" +"Content-Disposition: form-data; name=\"newAreaNo\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"monthPayDate\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"productType\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"perPageCount\""+"\r\n" +"\r\n" +"15"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"turntovalue\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"pageTurn\""+"\r\n" +"\r\n" +"YES"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"currPage\""+"\r\n" +"\r\n" +"1"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"method\""+"\r\n" +"\r\n" +"queryP2pPaymentAppointmentInfo"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"selectlist\""+"\r\n" +"\r\n" +"#"+"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"drFileType\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"uploadFile\"; filename=\"\""+"\r\n" +"Content-Type: application/octet-stream"+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n" +"Content-Disposition: form-data; name=\"dcFileType\""+"\r\n" +"\r\n" +"\r\n" +"------WebKitFormBoundaryx43rZoh62YQipnV1--"+"\r\n"; try { String xx=x.post("http://sit1-credit.zhph.lan/p2pPaymentAppointmentAction.do",map,param); System.out.println(xx); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }