java如何根據(jù)PostMan發(fā)送請求設(shè)置接口請求工具類
java根據(jù)PostMan發(fā)送請求:設(shè)置接口請求工具類
我們使用java代碼進(jìn)行接口遠(yuǎn)程調(diào)用第三方接口時,總會抒寫接口代碼,那么有這么多種方式進(jìn)行發(fā)送請求。那我們應(yīng)該怎么使用呢?
比如有webservice接口,比如有Post請求的接口,必須有Get請求的接口。比如傳的參數(shù)有xml的形式,比如傳的參數(shù)有json格式等等格式情況,那我們的接口請求代碼應(yīng)該如何區(qū)別,抒寫呢?
我們要根據(jù)postMan中的方式來,只要是能夠通過postMan發(fā)送成功的請求都可以使用
首先是我們的請求方式
第一點(diǎn):在postMan的請求方式有:GET、POST、PUT、DELETE請求。
第二點(diǎn):在PostMan中我們需要傳入url鏈接,那么new HttpGet(url)這里面的url就是鏈接地址。
GET:HttpGet httpGet = new HttpGet(url); POST:HttpPost method = new HttpPost(url); PUT:HttpPut put = new HttpPut(url); DELETE:HttpDelete delete = new HttpDelete(url);
第三點(diǎn):在PostMan中我們需要Params的時候:
HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter("",""); httpParams.setParameter("",""); httpParams.setParameter("",""); method.setParams(httpParams);
第四點(diǎn):在PostMan中我們需要設(shè)置Headers,其中方token或者字節(jié)編碼的時候很使用。
HttpPost method = new HttpPost(url); method.addHeader("",""); method.addHeader("",""); method.addHeader("","");
第五點(diǎn):在PostMan中我們需要設(shè)置Body,其中需要傳入?yún)?shù),不管是xml還是json都可以。那么我們需要設(shè)置兩個地方。
1、在第四點(diǎn)中的header中需要設(shè)置傳入?yún)?shù)的是xml還是json:
method.addHeader("Content-Type","application/json;");這里是json method.addHeader("Content-Type","application/xml;");這里是xml
2、在傳回來的參數(shù)中我們需要設(shè)置返回的數(shù)據(jù)類型和字符編碼集:param是發(fā)送的body參數(shù)。
StringEntity entity = new StringEntity(param, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json;"); method.setEntity(entity);//放入到method請求中。
第六點(diǎn):這樣進(jìn)行發(fā)送請求:method是集合請求方式,Params,Headers,body參數(shù)以后的集合。然后進(jìn)行發(fā)送。
CloseableHttpClient httpClient = HttpClients.createDefault();//得到發(fā)送。 HttpResponse resultRep = httpClient.execute(method);
第七點(diǎn):在PostMan中返回的數(shù)據(jù),我們需要如下來接收:
/請求發(fā)送成功,并得到響應(yīng)/
if (resultRep.getStatusLine().getStatusCode() == 200) { String str = ""; /**讀取服務(wù)器返回過來的json字符串?dāng)?shù)據(jù)**/ log.info("=========測試"+resultRep.toString()); String str4 = EntityUtils.toString(resultRep.getEntity()); log.info("========str4"+str4); result = str4; }
舉例如下
第一種方法:
public static String getwebserviceNew(String method,String serviceUrl,String user,String pw,String param){ try { //第一步:選擇請求方式: PostMethod postMethod = null; postMethod = new PostMethod(); postMethod.setPath(serviceUrl); String auth = "bearer "+pw; //第二步:設(shè)置header參數(shù) postMethod.addRequestHeader("Authorization", auth); postMethod.setRequestHeader("Content-Type", "text/xml") ; //第三步:得到需要發(fā)送的body String xmlInfo = getXmlInfo(method,user,pw,param); //第四步:設(shè)置發(fā)送的參數(shù)編碼集: postMethod.setRequestEntity(new StringRequestEntity(xmlInfo.toString(),"application/xml","UTF-8")); org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); //第五步:發(fā)送請求: int response = httpClient.executeMethod(postMethod); // 執(zhí)行POST方法 log.info("response--接口狀態(tài)碼-->"+response); String result = postMethod.getResponseBodyAsString() ; log.info("result-接口返回值-->"+result); return result; } catch (Exception e) { log.info("e----->"+e); //logger.info("請求異常"+e.getMessage(),e); throw new RuntimeException(e.getMessage()); } } private static String getXmlInfo(String method,String fydm,String token,String xml) { StringBuilder sb = new StringBuilder(); sb.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:szft='http://szft.tdh/'>"); sb.append("<soapenv:Header/>"); sb.append("<soapenv:Body>"); sb.append("<szft:"+method+">"); sb.append("<fydm>"+fydm+"</fydm>"); sb.append("<token>"+token+"</token>"); sb.append("<xml>"+xml+"</xml>"); sb.append("</szft:"+method+">"); sb.append("</soapenv:Body>"); sb.append("</soapenv:Envelope>"); return sb.toString(); }
第二種方法:
/** * http請求接口,獲取通達(dá)海token和獲取通達(dá)海代理人使用 * post請求 * @param url url地址 * @param param 請求參數(shù) * @param token token * @param ContentType 發(fā)送數(shù)據(jù)類型 * @return * @throws IOException * @throws ClientProtocolException */ public static String httpPostAllAgent(String url,String param,String token,String ContentType) throws ClientProtocolException, IOException{ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } url = URLDecoder.decode(url, "UTF-8"); CloseableHttpClient httpClient = HttpClients.createDefault(); String result = null; HttpPost method = new HttpPost(url); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("Content-Type", ContentType); headers.put("Accept-Charset", "charset=utf-8"); headers.put("Authorization", token); for (Map.Entry<String, Object> head : headers.entrySet()) { method.addHeader(head.getKey(), String.valueOf(head.getValue())); } //設(shè)置請求訪問時間 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60).setConnectTimeout(1000*60).build();//設(shè)置請求和傳輸超時時間 method.setConfig(requestConfig); if (null != param) { StringEntity entity = new StringEntity(param, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType(ContentType); method.setEntity(entity); } HttpResponse resultRep = httpClient.execute(method); /**請求發(fā)送成功,并得到響應(yīng)**/ if (resultRep.getStatusLine().getStatusCode() == 200) { String str = ""; /**讀取服務(wù)器返回過來的json字符串?dāng)?shù)據(jù)**/ log.info("=========測試"+resultRep.toString()); String str4 = EntityUtils.toString(resultRep.getEntity()); log.info("========str4"+str4); result = str4; } return result; }
multipart/form-data請求方式:
public static String uploadFile(String url, Map<String, Object> mapData){ CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; //每個post參數(shù)之間的分隔。隨意設(shè)定,只要不會和其他的字符串重復(fù)即可。 String boundary ="----WebKitFormBoundary5ZMULAAn6mngkXzn"; try { HttpPost httpPost = new HttpPost(url); //設(shè)置請求頭 httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary); //HttpEntity builder MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //字符編碼 builder.setCharset(Charset.forName("UTF-8")); //模擬瀏覽器 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //boundary builder.setBoundary(boundary); //multipart/form-data // builder.addPart("multipartFile",new FileBody(filePath)); // binary // builder.addBinaryBody("name=\"multipartFile\"; filename=\"test.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流 // //其他參數(shù) for (String key : mapData.keySet()) { builder.addTextBody(key, mapData.get(key).toString(), ContentType.create("text/plain", Consts.UTF_8)); } //HttpEntity HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 執(zhí)行提交 HttpResponse response = httpClient.execute(httpPost); //響應(yīng) HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 將響應(yīng)內(nèi)容轉(zhuǎn)換為字符串 result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } System.err.println("result"+result); return result; }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
springboot日志文件名稱叫l(wèi)ogback-spring.xml的原因解析
這篇文章主要介紹了springboot日志文件名稱為什么叫l(wèi)ogback-spring.xml,本文給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08Springboot logback-spring.xml無法加載問題
這篇文章主要介紹了Springboot logback-spring.xml無法加載問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05SpringBoot使用Validator進(jìn)行參數(shù)校驗實戰(zhàn)教程(自定義校驗,分組校驗)
這篇文章主要介紹了SpringBoot使用Validator進(jìn)行參數(shù)校驗(自定義校驗,分組校驗)的實戰(zhàn)教程,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2023-07-07idea打包java可執(zhí)行jar包的實現(xiàn)步驟
這篇文章主要介紹了idea打包java可執(zhí)行jar包的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12