HttpClient API:
The most essential function of HttpClient is to execute HTTP methods.
Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges,
usually handled internally by HttpClient.
The user is expected to provide a request object to execute and HttpClient is expected to transmit the request to the target server return a corresponding response object,
or throw an exception if execution was unsuccessful. The main entry point of the HttpClient API is
the HttpClient interface that defines the contract described above.
Reference: http://www.apache.org/
Prerequisites:-----
Following jar files are required (httpcomponents-client-4.3.4):
commons-codec-1.9.jar
commons-logging-1.1.3.jar
fluent-hc-4.3.4.jar
httpclient-4.3.4.jar
httpclient-cache-4.3.4.jar
httpcore-4.3.2.jar
httpmime-4.3.4.jar
----------------------------------------------------------------------------------------------------
HttpUtils utility class
----------------------------------------------------------------------------------------------------
/*
* Created By: Abhinav Kumar Mishra
* Copyright © 2014. Abhinav Kumar
Mishra.
* All rights reserved.
*
* Licensed under the Apache License, Version
2.0 (the "License");
* you may not use this file except in
compliance with the License.
* You may obtain a copy of the License at
*
*
http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or
agreed to in writing, software
* distributed under the License is
distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.
* See the License for the specific language
governing permissions and
* limitations under the License.
*/
package
com.github.abhinavmishra14.http.utils;
import
java.io.InputStream;
import
java.nio.charset.StandardCharsets;
import
java.security.KeyManagementException;
import
java.security.NoSuchAlgorithmException;
import java.util.List;
import
javax.net.ssl.SSLContext;
import
org.apache.commons.io.IOUtils;
import
org.apache.commons.logging.Log;
import
org.apache.commons.logging.LogFactory;
import
org.apache.http.HttpResponse;
import
org.apache.http.NameValuePair;
import
org.apache.http.auth.AuthScope;
import
org.apache.http.auth.UsernamePasswordCredentials;
import
org.apache.http.client.ClientProtocolException;
import
org.apache.http.client.CredentialsProvider;
import
org.apache.http.client.entity.UrlEncodedFormEntity;
import
org.apache.http.client.methods.HttpDelete;
import
org.apache.http.client.methods.HttpGet;
import
org.apache.http.client.methods.HttpPost;
import
org.apache.http.client.methods.HttpPut;
import
org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import
org.apache.http.conn.ssl.SSLContexts;
import
org.apache.http.entity.StringEntity;
import
org.apache.http.impl.client.BasicCredentialsProvider;
import
org.apache.http.impl.client.CloseableHttpClient;
import
org.apache.http.impl.client.HttpClients;
import
java.io.IOException;
/**
* The Class HTTPUtils.
*/
public final class HTTPUtils {
/** The Constant HTTP_CODE_401. */
public static final int HTTP_CODE_401 =
401;
/** The Constant HTTP_CODE_400. */
public static final int HTTP_CODE_400 =
400;
/** The Constant HTTP_CODE_403. */
public static final int HTTP_CODE_403 =
403;
/** The Constant HTTP_CODE_404. */
public static final int HTTP_CODE_404 =
404;
/** The Constant HTTP_CODE_500. */
public static final int HTTP_CODE_500 =
500;
/** The Constant HTTP_CODE_409. */
public static final int HTTP_CODE_409 =
409;
/** The Constant HTTP_CODE_200. */
public static final int HTTP_CODE_200 =
200;
/** The Constant HTTP_CODE_201. */
public static final int HTTP_CODE_201 =
201;
/** The Constant MIME_JSON. */
public static final String MIME_JSON =
"application/json";
/** The Constant UTF8 */
public static final String UTF8 = "UTF-8";
/** The Constant LOG. */
private final static Log LOG =
LogFactory.getLog(HTTPUtils.class);
/**
* The Constructor.
*/
private HTTPUtils() {
super();
}
/**
* Execute http get.
*
* @param url the url
* @return the input stream
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static HttpResponse
httpGet(final String url)
throws
ClientProtocolException, IOException,
KeyManagementException,
NoSuchAlgorithmException {
LOG.info("Sending
http get with url: "+ url);
final
CloseableHttpClient httpclient = getHttpClient();
final HttpGet request = new HttpGet(url);
return
httpclient.execute(request);
}
/**
* Execute http get.
*
* @param url the url
* @param userName the user name
* @param password the password
* @return the input stream
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static HttpResponse
httpGet(final String url, final String userName,
final String password) throws
ClientProtocolException, IOException,
KeyManagementException,
NoSuchAlgorithmException {
LOG.info("Sending
http get with url: "+ url);
final CloseableHttpClient httpclient =
getHttpClient(userName, password);
final HttpGet request = new HttpGet(url);
return
httpclient.execute(request);
}
/**
* Http post.
*
* @param url the url
* @param jsonReqData the json req data
* @param userName the user name
* @param password the password
* @return the http response
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static HttpResponse
httpPost(final String url,
final String
jsonReqData, final String userName,
final String password) throws
ClientProtocolException, IOException,
KeyManagementException,
NoSuchAlgorithmException {
LOG.info("Sending
http post with url: "+ url);
final CloseableHttpClient httpclient =
getHttpClient(userName, password);
final HttpPost httpPost
= new HttpPost(url);
final StringEntity
httpEntity = new StringEntity(jsonReqData, UTF8);
httpEntity.setContentType(MIME_JSON);
httpPost.setEntity(httpEntity);
return
httpclient.execute(httpPost);
}
/**
* Http post.
*
* @param url the url
* @param jsonReqData the json req data
* @return the http response
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static HttpResponse
httpPost(final String url,
final String
jsonReqData) throws ClientProtocolException,
IOException,
KeyManagementException, NoSuchAlgorithmException {
LOG.info("Sending
http post with url: "+ url);
final
CloseableHttpClient httpclient = getHttpClient();
final HttpPost httpPost
= new HttpPost(url);
final StringEntity
httpEntity = new StringEntity(jsonReqData, UTF8);
httpEntity.setContentType(MIME_JSON);
httpPost.setEntity(httpEntity);
return
httpclient.execute(httpPost);
}
/**
* Http post.
*
* @param url the url
* @param params the params
* @return the http response
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static HttpResponse
httpPost(final String url,
final
List<NameValuePair> params) throws ClientProtocolException,
IOException,
KeyManagementException, NoSuchAlgorithmException {
LOG.info("Sending
http post with url: "+ url+ " params: "+params);
final
CloseableHttpClient httpclient = getHttpClient();
final HttpPost httpPost
= new HttpPost(url);
httpPost.setEntity(new
UrlEncodedFormEntity(params, UTF8));
return
httpclient.execute(httpPost);
}
/**
* Http put.
*
* @param url the url
* @param jsonReqData the json req data
* @return the http response
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static HttpResponse
httpPut(final String url,
final String
jsonReqData) throws ClientProtocolException,
IOException,
KeyManagementException, NoSuchAlgorithmException {
LOG.info("Sending
http put with url: "+ url);
final
CloseableHttpClient httpclient = getHttpClient();
final HttpPut httpPut = new HttpPut(url);
final StringEntity
httpEntity = new StringEntity(jsonReqData, UTF8);
httpEntity.setContentType(MIME_JSON);
httpPut.setEntity(httpEntity);
return
httpclient.execute(httpPut);
}
/**
* Http put.
*
* @param url the url
* @param jsonReqData the json req data
* @param userName the user name
* @param password the password
* @return the http response
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static HttpResponse
httpPut(final String url,
final String
jsonReqData, final String userName,
final String password) throws
ClientProtocolException, IOException,
KeyManagementException,
NoSuchAlgorithmException {
LOG.info("Sending
http put with url: "+ url);
final CloseableHttpClient httpclient =
getHttpClient(userName, password);
final HttpPut httpPut = new HttpPut(url);
final StringEntity
httpEntity = new StringEntity(jsonReqData, UTF8);
httpEntity.setContentType(MIME_JSON);
httpPut.setEntity(httpEntity);
return
httpclient.execute(httpPut);
}
/**
* Http delete.
*
* @param url the url
* @return the http response
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static HttpResponse
httpDelete(final String url)
throws
ClientProtocolException, IOException,
KeyManagementException,
NoSuchAlgorithmException {
LOG.info("Sending
http delete with url: "+ url);
final
CloseableHttpClient httpclient = getHttpClient();
final HttpDelete
httpDelete = new HttpDelete(url);
return
httpclient.execute(httpDelete);
}
/**
* Http delete.
*
* @param url the url
* @param jsonReqData the json req data
* @param userName the user name
* @param password the password
* @return the http response
* @throws ClientProtocolException the
client protocol exception
* @throws IOException the IO exception
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static HttpResponse
httpDelete(final String url,
final String jsonReqData, final String userName,
final String password) throws
ClientProtocolException, IOException,
KeyManagementException,
NoSuchAlgorithmException {
LOG.info("Sending
http delete with url: "+ url);
final CloseableHttpClient httpclient =
getHttpClient(userName, password);
final HttpDelete
httpDelete = new HttpDelete(url);
return
httpclient.execute(httpDelete);
}
/**
* Gets the http client.
*
* @return the http client
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static
CloseableHttpClient getHttpClient()
throws KeyManagementException, NoSuchAlgorithmException
{
final SSLContext
sslContext = SSLContexts.custom().useTLS().build();
final
SSLConnectionSocketFactory sslConnFactory =
new
SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"},
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//Returns the CloseableHttpClient
return HttpClients.custom().setSSLSocketFactory(sslConnFactory).build();
}
/**
* Gets the http client.
*
* @param username the username
* @param password the password
* @return the http client
* @throws KeyManagementException the key
management exception
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static
CloseableHttpClient getHttpClient(final String username,
final String password) throws
KeyManagementException,
NoSuchAlgorithmException {
final
CredentialsProvider provider = new BasicCredentialsProvider();
final
UsernamePasswordCredentials credentials =
new
UsernamePasswordCredentials(username, password);
provider.setCredentials(AuthScope.ANY,
credentials);
final SSLContext
sslContext = SSLContexts.custom().useTLS().build();
final
SSLConnectionSocketFactory sslConnFactory =
new
SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"}, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setDefaultCredentialsProvider(
provider).setSSLSocketFactory(sslConnFactory).build();
}
/**
* Convert stream to string.
*
* @param responseStream the response stream
* @return the string
* @throws IOException the IO exception
*/
public static String
convertStreamToString(final InputStream responseStream)
throws IOException {
return
IOUtils.toString(responseStream,StandardCharsets.UTF_8);
}
/**
* Gets the hashed password.
*
* @param password the password
* @return the hashed password
* @throws NoSuchAlgorithmException the no
such algorithm exception
*/
public static String
getHashedPassword(final String password)
throws
NoSuchAlgorithmException {
final MessageDigest
mDigest = MessageDigest.getInstance("sha1");
final byte[] digestPassword =
mDigest.digest(password.getBytes(StandardCharsets.UTF_8));
final StringBuffer
digestPassSb = new StringBuffer();
for (int index = 0; index
< digestPassword.length; index++) {
digestPassSb.append(Integer.toString((digestPassword[index]
& 0xff) +
0x100,16).substring(1));
}
return
digestPassSb.toString();
}
/**
* Read binary content.
*
* @param filePath the file path
* @return the byte[]
* @throws IOException the IO exception
*/
public static byte[]
readBinaryContent(final String filePath)
throws IOException {
byte[] binaryData = null;
try (final FileInputStream
inputStream = new FileInputStream(
filePath);) {
try (final
ByteArrayOutputStream outputStream =
new
ByteArrayOutputStream();) {
final int bufferSize = 1
<< 8; // 1KiB buffer
final byte[] buffer = new byte[bufferSize];
int bytesRead = -1;
while ((bytesRead =
inputStream.read(buffer)) > -1) {
outputStream.write(buffer,
0, bytesRead);
}
binaryData =
outputStream.toByteArray();
}
}
return binaryData;
}
/**
* Read binary content from input stream.
*
* @param inputStream the input stream
* @return the byte[]
* @throws IOException the IO exception
*/
public static byte[]
readBinaryContent(final InputStream inputStream )
throws IOException {
byte[] binaryData = null;
try (final
ByteArrayOutputStream outputStream =
new
ByteArrayOutputStream();) {
final int bufferSize = 1
<< 8; // 1KiB buffer
final byte[] buffer = new byte[bufferSize];
int bytesRead = -1;
while ((bytesRead =
inputStream.read(buffer)) > -1) {
outputStream.write(buffer,
0, bytesRead);
}
binaryData =
outputStream.toByteArray();
}
return binaryData;
}
/**
* Encode bytes to base64.
*
* @param binaryData the binary data
* @return the string
*/
public static String
encodeBytesToBase64String(final byte[] binaryData){
return
Base64.encodeBase64String(binaryData);
}
/**
* Encode bytes to base64.
*
* @param binaryData the binary data
* @return the byte[]
*/
public static byte[]
encodeBytesToBase64(final byte[] binaryData){
return
Base64.encodeBase64(binaryData);
}
/**
* Decode bse64 string to bytes.
*
* @param encodedStr the encoded str
* @return the byte[]
*/
public static byte[]
decodeBse64StringToBytes(final String encodedStr){
return
Base64.decodeBase64(encodedStr);
}
/**
* Write byte array to file.
*
* @param binaryData the binary data
* @param filePath the file path
* @throws FileNotFoundException the file
not found exception
* @throws IOException the IO exception
*/
public static void
writeByteArrayToFile(final byte[] binaryData,
final String filePath)
throws
FileNotFoundException, IOException {
try (FileOutputStream
fileOpStream = new FileOutputStream(filePath);) {
fileOpStream.write(binaryData);
}
}
/**
* Save stream to file.
*
* @param inputStream the input stream
* @param fileName the file name
* @throws FileNotFoundException the file
not found exception
* @throws IOException the IO exception
*/
public static void saveStreamToFile(final InputStream
inputStream,
final String fileName)
throws
FileNotFoundException, IOException {
writeByteArrayToFile(readBinaryContent(inputStream),fileName);
}
}
|
No comments:
Post a Comment
Thanks for your comments/Suggestions.