Invoking an HTTP Request
You can use an HTTP client resource to invoke HTTP requests from component implementations. A POST example illustrates this.
Procedure
Post Example
The following example demonstrates how to invoke an HTTP Post request
using an HTTP client object retrieved from the HTTP client connection factory
or using an HTTP connection:
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
public GetQuoteResponseDocument getQuote(GetQuoteDocument parameters) {
String symbol = parameters.getGetQuote().getSymbol();
String value = ERROR_MSG;
try {
/**
* Two ways of using HTTP client API, randomly selected at runtime:
* a) HTTP Client
* b) HTTP Connection
*/
if(random.nextBoolean()){
value = getQuoteUsingHttpClient(getHttpConnectionFactory(), symbol.trim());
}else{
value = getQuoteUsingHttpConnection(getHttpConnectionFactory(), symbol.trim());
}
} catch (Exception e) {
if(logger.isErrorEnabled()){
logger.error(ERROR_MSG,e);
}
}
GetQuoteResponseDocument responseDoc = GetQuoteResponseDocument.Factory.newInstance();
responseDoc.addNewGetQuoteResponse().setGetQuoteResult(value);
return responseDoc;
}
/**
* Processes the request using HTTPClient API
*/
private String getQuoteUsingHttpClient(HttpClientConnectionFactory connectionFactory,
String symbol) throws HttpException, ClientProtocolException, IOException {
String responseString = ERROR_MSG;
String message = getContent(symbol);
byte[] bytes = message.getBytes();
/** HTTPClient provides a facade to a number of special purpose handler or strategy
* implementations responsible for handling of a particular aspect of
* the HTTP protocol such as redirect or authentication handling or
* making decision about connection persistence and keep alive duration.
* This allows you to selectively replace the default implementation
* of those aspects with custom, application-specific ones.
*/
HttpClientWrapper httpClient = connectionFactory.getHttpClient();
HttpHost configuration = connectionFactory.getHostConfiguration();
/**
* Construct the request URL
*/
String url = configuration.getSchemeName() + "://"+ configuration.getHostName()+":"+
configuration.getPort() + "/stockquote.asmx";
/**
* Prepare request object and its header for HTTP Post request
*/
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/xml; charset=utf-8");
httpPost.setHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
/**
* Sets the Entity to handle content management.
*/
ByteArrayInputStream instream = new ByteArrayInputStream(bytes);
InputStreamEntity e2 = new InputStreamEntity(instream, -1);
httpPost.setEntity(e2);
/**
* Execute the POST URL using HttpClientWrapper which takes care of
* connection management other functionality internally.
*/
HttpResponse response = httpClient.execute(httpPost);
/**
* Get the response Entity which holds the response content from HttpResponse.
*/
HttpEntity resEntity = response.getEntity();
//Reads the response
responseString = getResponseString(resEntity);
if (resEntity != null) {
/**
* The Method consumeContent() is called to indicate that the content of this entity
* is no longer required. All entity implementations are expected to
* release all allocated resources as a result of this method
* invocation.
*/
resEntity.consumeContent();
}
return responseString;
}
/**
* Processes the request using HTTPConnection API
*/
private String getQuoteUsingHttpConnection(HttpClientConnectionFactory connectionFactory,
String symbol) throws HttpException, IOException {
String responseString = ERROR_MSG;
String message = getContent(symbol);
byte[] bytes = message.getBytes();
HttpClientConnection httpClientConnection = connectionFactory.getHttpConnection();
HttpHost configuration = connectionFactory.getHostConfiguration();
/**
* Construct the request URL
*/
String url = configuration.getSchemeName() + "://"+ configuration.getHostName() +":"+
configuration.getPort() + "/stockquote.asmx";
try {
/**
* Prepare request object and its header for HTTP Post request
*/
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/xml; charset=utf-8");
httpPost.setHeader("SOAPAction","http://www.webserviceX.NET/GetQuote");
/**
* Sets the Entity to handle content management.
*/
ByteArrayInputStream instream = new ByteArrayInputStream(bytes);
InputStreamEntity e2 = new InputStreamEntity(instream, -1);
httpPost.setEntity(e2);
/**
* Set HTTP params on Post request object
*/
httpPost.setParams(connectionFactory.getHttpParams());
/** HttpContext represents execution state of an HTTP process.
* It is a structure that can be used to map an attribute name
* to an attribute value. Internally HTTP context implementations
* are usually backed by a HashMap.
*/
BasicHttpContext basicHttpContext = new BasicHttpContext(null);
// Populate the execution context
basicHttpContext.setAttribute(ExecutionContext.HTTP_CONNECTION,httpClientConnection);
basicHttpContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST,connectionFactory.
getHostConfiguration());
basicHttpContext.setAttribute(ExecutionContext.HTTP_REQUEST,httpPost);
/** HTTP protocol processor is a collection of protocol interceptors that
* implements the Chain of Responsibility pattern, where each individual
* protocol interceptor is expected to work on a particular aspect of the HTTP
* protocol for which the interceptor is responsible.
*/
BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
// Required request interceptors
httpProcessor.addInterceptor(new RequestContent());
httpProcessor.addInterceptor(new RequestTargetHost());
// Recommended request interceptors
httpProcessor.addInterceptor(new RequestConnControl());
httpProcessor.addInterceptor(new RequestUserAgent());
httpProcessor.addInterceptor(new RequestExpectContinue());
/** HttpRequestExecutor is a client side HTTP protocol handler based on the
* blocking I/O model that implements the essential requirements of the HTTP
* protocol for the client side message processing
*/
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
// Prepare request
httpexecutor.preProcess(httpPost, httpProcessor, basicHttpContext);
// Execute request and get a response
HttpResponse response = httpexecutor.execute(httpPost,httpClientConnection,
basicHttpContext);
// Finalize response
httpexecutor.postProcess(response, httpProcessor, basicHttpContext);
HttpEntity resEntity = response.getEntity();
//Reads the response
responseString = getResponseString(resEntity);
if (resEntity != null) {
/**
* The Method consumeContent() is called to indicate that the content of this entity
* is no longer required. All entity implementations are expected to
* release all allocated resources as a result of this method
* invocation.
*/
resEntity.consumeContent();
}
} finally {
httpClientConnection.close();
}
return responseString;
}
/**
* Reads and returns the string content from response Entity
*/
private String getResponseString(HttpEntity resEntity)
throws IOException {
if (resEntity != null) {
InputStream content = resEntity.getContent();
byte[] cbytes = new byte[new Long(1000).intValue()];
int x = -1;
StringBuilder sb = new StringBuilder();
while ((x = content.read(cbytes)) != -1) {
String reponseContent = new String(cbytes);
sb.append(reponseContent);
}
return getValue(sb.toString().trim());
}
return ERROR_MSG;
}
/**
* Returns the request content.
* @param symbol
* @return
*/
private String getContent(String symbol) {
return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"
+ "xmlns:web=\"http://www.webserviceX.NET/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<web:GetQuote>"
+ "<web:symbol>"+symbol+"</web:symbol>"
+ "</web:GetQuote>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
}
Copyright © Cloud Software Group, Inc. All rights reserved.