Tuesday, 28 August 2018

HTTP connection via program


HTTP connection via program

Using the below code snippet, We can call/invoke the external URL using GET/POST method.

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;



HttpConnectionManagerParams httpParams = new HttpConnectionManagerParams();
SimpleHttpConnectionManager localSimpleHttpConnectionManager = new SimpleHttpConnectionManager();
httpParams.setConnectionTimeout((int) Long.parseLong(getAkamaiCacheConnectionTimeOut()));
localSimpleHttpConnectionManager.setParams(httpParams);
HttpClient localHttpClient = new HttpClient(localSimpleHttpConnectionManager);

// proxy is requried only in local enviroment. Not required at higher environments.
if (isEnableProxyFlag()) {
if (isLoggingDebug()) {
logDebug("Inside proxy check block");
}
//lProxy_host,lProxyPort are specific environment related proxy information.
String lProxy_host = (String) getProxyMap().get("proxyHost");
int lProxyPort = Integer.parseInt((String) getProxyMap().get("proxyPort"));
localHttpClient.getHostConfiguration().setProxy((String) lProxy_host, lProxyPort);
userObject = (String) getProxyMap().get("proxyUserName");
password = (String) getProxyMap().get("proxyPassword");
if ((userObject != null) && (password != null)
&& ("true".equalsIgnoreCase((String) getProxyMap().get("proxyAuthrequired")))) {
responseObject = new UsernamePasswordCredentials((String) userObject, password);
localHttpClient.getState().setProxyCredentials(new AuthScope((String) lProxy_host, lProxyPort),
(Credentials) responseObject);
}
}

try {
String nodeUrl ="some external system URL toinvoked"

postURL = new URL(nodeUrl);
//using the getmethod as URL to be invoked team speficied.It may be post method also. based on requirement.
getMethod = new GetMethod(postURL.toString());
int httpReponseCode = localHttpClient.executeMethod(getMethod);

}} catch (HttpException e1) {
if (isLoggingError()) {
logError(" HttpException occurs");
logError("Not able to connect to url " + nodeUrl);
}
} catch (MalformedURLException e1) {
if (isLoggingError()) {
logError(" MalformedURLException occurs ");
logError("Not able to connect to url " + nodeUrl);
}

} catch (IOException e1) {
if (isLoggingError()) {
logError(" IOException occurs ");
logError("Not able to connect to url " + nodeUrl);
}
}


}

Requried JARs
The following jars are required for this.

lib/org-apache-commons-codec.jar lib/org.apache.commons.httpclient.jar and need to add as part of META-INF/MANIFEST.MF

No comments:

Post a Comment