How To Post Http Asking Using Apache Httpcomponents Library

There are many ways to transportation asking to a server as well as ane of them is past times using http customer library. But this library has ii versions now. The one-time httpclient as well as this httpcomponents. We volition furnish a sample code to endeavour the latter.

But earlier that nosotros request to add together maven dependency to our project, this is assuming y'all are working on a maven project.

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency>  <groupId>org.apache.httpcomponents</groupId>  <artifactId>httpclient</artifactId>  <version>4.3.4</version> </dependency> 

Influenza A virus subtype H5N1 method that sends post service asking alongside variables:

public static String postRequest(String url, Map<String, String> params) throws IOException {  log.debug("sending POST asking to={}, params={}", url, params);   endeavour (CloseableHttpClient httpClient = HttpClients.createDefault()) {   List<NameValuePair> postParameters = novel ArrayList<>();    // add together post service parameters   params.forEach((key, value) -> {    postParameters.add(new BasicNameValuePair(key, value));   });    // initialize the post service asking   HttpPost httpPost = novel HttpPost(url);   httpPost.setEntity(new UrlEncodedFormEntity(postParameters));    StringBuilder responseString = novel StringBuilder();    // execute the asking   HttpResponse reply = httpClient.execute(httpPost);    // read the reply   if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {    HttpEntity responseHttpEntity = response.getEntity();    InputStream content = responseHttpEntity.getContent();     BufferedReader buffer = novel BufferedReader(new InputStreamReader(content));    String line;    spell ((line = buffer.readLine()) != null) {     responseString.append(line);    }     // unloose all resources held past times the responseHttpEntity    EntityUtils.consume(responseHttpEntity);     log.debug("html-------\r\n" + responseString);     render responseString.toString();   } else {    log.error("Error sending asking alongside status=" + response.getStatusLine().getStatusCode());   }   }   render ""; } 

And live a sample method call:

public Map<String, String> params= novel HashMap<>(); params.put("param1", "value1"); params.put("param2", "value2"); params.put("param3", "value3");  MyClass.postRequest(AppSettings.MEMBER_NAME_URL, params); 
Next
Previous
Click here for Comments

0 komentar:

Please comment if there are any that need to be asked.