Java sends requests based on PostMan: Set interface request tool class
When we use Java code to remotely call third-party interfaces, we always write interface code, so there are so many ways to send requests. So how should we use it?
For example, there is a webservice interface, or an interface with Post request, there must be a interface with Get request. For example, if the passed parameters are in the form of xml, if the passed parameters are in the form of json format, etc., then how should our interface request code be different and what should be written?
We need to use it according to the method in postMan. As long as you can send a successful request through postMan, you can use it
First of all, our request method
The first point: The request methods in postMan are: GET, POST, PUT, DELETE requests.
The second point: In PostMan, we need to pass in the url link, so the url in new HttpGet(url) is the link address.
GET:HttpGet httpGet = new HttpGet(url); POST:HttpPost method = new HttpPost(url); PUT:HttpPut put = new HttpPut(url); DELETE:HttpDelete delete = new HttpDelete(url);
Third point: When we need Params in PostMan:
HttpParams httpParams = new BasicHttpParams(); ("",""); ("",""); ("",""); (httpParams);
Fourth point: In PostMan, we need to set headers, which are very useful when encoding tokens or bytes.
HttpPost method = new HttpPost(url); ("",""); ("",""); ("","");
The fifth point: In PostMan, we need to set the Body, which requires passing in parameters, whether it is xml or json. Then we need to set up two places.
1. In the header in the fourth point, whether the incoming parameters need to be set:
("Content-Type","application/json;");here it isjson ("Content-Type","application/xml;");here it isxml
2. In the parameters sent back, we need to set the returned data type and character encoding set: param is the sent body parameter.
StringEntity entity = new StringEntity(param, "utf-8"); ("UTF-8"); ("application/json;"); (entity);//Put inmethodRequesting。
The sixth point: Send a request in this way: method is the collection request method, Params, Headers, and body parameters. Then send.
CloseableHttpClient httpClient = ();//Get sent. HttpResponse resultRep = (method);
Point 7: We need to receive the data returned in PostMan as follows:
/The request was sent successfully and received a response/
if (().getStatusCode() == 200) { String str = ""; /**Read the json string data returned by the server**/ ("=========test"+()); String str4 = (()); ("========str4"+str4); result = str4; }
For example,
The first method:
public static String getwebserviceNew(String method,String serviceUrl,String user,String pw,String param){ try { //Step 1: Select the request method: PostMethod postMethod = null; postMethod = new PostMethod(); (serviceUrl); String auth = "bearer "+pw; //Step 2: Set the header parameters ("Authorization", auth); ("Content-Type", "text/xml") ; //Step 3: Get the body that needs to be sent String xmlInfo = getXmlInfo(method,user,pw,param); //Step 4: Set the sent parameter encoding set: (new StringRequestEntity((),"application/xml","UTF-8")); httpClient = new (); //Step 5: Send a request: int response = (postMethod); // Execute the POST method ("response--interface status code-->"+response); String result = () ; ("result-interface return value-->"+result); return result; } catch (Exception e) { ("e----->"+e); //("Request exception"+(),e); throw new RuntimeException(()); } } private static String getXmlInfo(String method,String fydm,String token,String xml) { StringBuilder sb = new StringBuilder(); ("<soapenv:Envelope xmlns:soapenv='/soap/envelope/' xmlns:szft='/'>"); ("<soapenv:Header/>"); ("<soapenv:Body>"); ("<szft:"+method+">"); ("<fydm>"+fydm+"</fydm>"); ("<token>"+token+"</token>"); ("<xml>"+xml+"</xml>"); ("</szft:"+method+">"); ("</soapenv:Body>"); ("</soapenv:Envelope>"); return (); }
The second method:
/** * http request interface, obtain Tongdahai token and obtain Tongdahai agent use * post request * @param url url address * @param param Request parameters * @param token token * @param ContentType Send data type * @return * @throws IOException * @throws ClientProtocolException */ public static String httpPostAllAgent(String url,String param,String token,String ContentType) throws ClientProtocolException, IOException{ try { (1); } catch (InterruptedException e) { (); } url = (url, "UTF-8"); CloseableHttpClient httpClient = (); String result = null; HttpPost method = new HttpPost(url); Map<String, Object> headers = new HashMap<String, Object>(); ("Content-Type", ContentType); ("Accept-Charset", "charset=utf-8"); ("Authorization", token); for (<String, Object> head : ()) { ((), (())); } //Set request access time RequestConfig requestConfig = ().setSocketTimeout(1000*60).setConnectTimeout(1000*60).build();//Set request and transfer timeout time (requestConfig); if (null != param) { StringEntity entity = new StringEntity(param, "utf-8"); ("UTF-8"); (ContentType); (entity); } HttpResponse resultRep = (method); /**Request sent successfully and received a response**/ if (().getStatusCode() == 200) { String str = ""; /**Read the json string data returned by the server**/ ("=========test"+()); String str4 = (()); ("========str4"+str4); result = str4; } return result; }
Multipart/form-data request method:
public static String uploadFile(String url, Map<String, Object> mapData){ CloseableHttpClient httpClient = (); String result = ""; //Separation between each post parameter. Set it at will, as long as it will not be repeated with other strings. String boundary ="----WebKitFormBoundary5ZMULAAn6mngkXzn"; try { HttpPost httpPost = new HttpPost(url); //Set request header ("Content-Type","multipart/form-data; boundary="+boundary); //HttpEntity builder MultipartEntityBuilder builder = (); //Character encoding (("UTF-8")); //Simulate the browser (HttpMultipartMode.BROWSER_COMPATIBLE); //boundary (boundary); //multipart/form-data // ("multipartFile",new FileBody(filePath)); // binary // ("name=\"multipartFile\"; filename=\"\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// File Streaming// //Other parameters for (String key : ()) { (key, (key).toString(), ("text/plain", Consts.UTF_8)); } //HttpEntity HttpEntity entity = (); (entity); // Perform a submission HttpResponse response = (httpPost); //response HttpEntity responseEntity = (); if (responseEntity != null) { // Convert the response content to a string result = (responseEntity, ("UTF-8")); } } catch (IOException e) { (); } catch (Exception e) { (); } finally { try { (); } catch (IOException e) { (); } } ("result"+result); return result; }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.