Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
jerry-http - Common Java Functionality Copyright (c) 2012-2014, Sandeep Gupta http://sangupta.com/projects/jerry-http 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.sangupta.jerry.http;
 
 import java.util.List;
 import java.util.Map;
 
 
Utility class containing methods pertaining to invocation of REST based webservices and capturing the responses obtained from the same. For advanced usage, the WebRequest facade can be used directly to gain much more control over the request/response handling. The methods in this class will timeout within one minute if no connection is established, or the socket timeout happens.

Author(s):
sangupta
Since:
0.1.0
 
 public class WebInvoker {

Value to be used for connection timeout
 
 	private static int CONNECTION_TIMEOUT = (int.;

Value to be used for socket timeout
 
 	private static int SOCKET_TIMEOUT = (int.;

An instance of WebInvocationInterceptor that needs to be used when handling interceptors. If an interceptor is added while a call is being made, it will not apply to that request. Interceptors will work only on a fresh request.
 
 	public static WebInvocationInterceptor interceptor = null;

My private logger
 
 	private static final Logger logger = LoggerFactory.getLogger(WebInvoker.class);

Return the HTTP response body for a GET request to the given URL. In case an java.io.IOException is thrown, it will be eaten up, logged at DEBUG level, and null returned.

Parameters:
url the url to hit
Returns:
the string response body
 
 	public static String fetchResponse(String url) {
 	}

Return the HTTP response body for a GET request to the given URL using the given cookie policy. In case an java.io.IOException is thrown, it will be eaten up, logged at DEBUG level, and null returned.

Parameters:
url the url to hit
cookiePolicy the cookie policy to use
Returns:
the string reponse body
	public static String fetchResponse(String urlString cookiePolicy) {
		try {
catch(IOException e) {
			.debug("Unable to fetch repsonse from url: {}"urle);
		}
		return null;
	}

Return the WebResponse for a GET request to the given URL using the org.apache.http.client.params.CookiePolicy.BEST_MATCH cookie policy . In case an java.io.IOException is thrown, it will be eaten up, logged at DEBUG level, and null returned.

Parameters:
url the url to hit
Returns:
the WebResponse obtained
	public static WebResponse getResponse(String url) {
	}

Return the entire response for a GET request to the given URL using the given cookie policy

Parameters:
url the url to hit
cookiePolicy the cookie policy to use
Returns:
the WebResponse obtained
	public static WebResponse getResponse(String urlString cookiePolicy) {
		try {
catch(Exception e) {
			.debug("Unable to fetch repsonse from url: {}"urle);
		}
		return null;
	}

Returns the HTTP headers etc by making a HEAD request to the given URL as a java.util.Map. A cookie policy of org.apache.http.client.params.CookiePolicy.BEST_MATCH is used.

Parameters:
url the url to hit
followRedirects whether redirects should be followed or not
Returns:
a map of all header values
	public static Map<StringStringgetHeaders(String urlboolean followRedirects) {
		return getHeaders(urlfollowRedirects.);
	}

Return the HTTP headers by making a HEAD request to the given URL using the given cookie policy

Parameters:
url the url to hit
followRedirects whether redirects should be followed or not
cookiePolicy the cookie policy to use
Returns:
a map of all header values
	public static Map<StringStringgetHeaders(String urlboolean followRedirectsString cookiePolicy) {
		try {
			if(followRedirects) {
			}
catch(IOException e) {
			.debug("Unable to fetch response headers from url: {}"urle);
		}
		return null;
	}

Make a HEAD request to the URL and return the web response. A cookie policy of org.apache.http.client.params.CookiePolicy.BEST_MATCH is used.

Parameters:
url the url to hit
followRedirects whether to follow redirects or not
Returns:
the WebResponse obtained
	public static WebResponse headRequest(String urlboolean followRedirects) {
		return headRequest(urlfollowRedirects.);
	}

Make a HEAD request to the URL using given cookie policy and return the web response.

Parameters:
url the url to hit
followRedirects whether to follow redirects or not
cookiePolicy the cookie policy to use
Returns:
the WebResponse obtained
	public static WebResponse headRequest(String urlboolean followRedirectsString cookiePolicy) {
		try {
			if(followRedirects) {
			}
catch(IOException e) {
			.debug("Unable to fetch response headers from url: {}"urle);
		}
		return null;
	}

Invoke the given URL by the specified HTTP verb/method and return the entire HTTP response.

Parameters:
uri the url to hit
method the VERB to use
Returns:
the WebResponse obtained
	public static WebResponse invokeUrl(final String urifinal WebRequestMethod method) {
		WebRequest request = getWebRequest(urimethod);
		try {
			return request.execute().webResponse();
catch(IOException e) {
			.debug("Unable to fetch repsonse from url: {}"urie);
		}
		return null;
	}

Invoke the given URL by the specified method, supplying the header and params as specified and return the entire HTTP response.

Parameters:
uri the url to hit
method the VERB to use
headers the request headers to be sent
params the FORM parameters to be sent
Returns:
the WebResponse obtained
	public static WebResponse invokeUrl(final String urifinal WebRequestMethod methodfinal Map<StringStringheadersfinal Map<StringStringparams) {
		WebRequest request = getWebRequest(urimethod);
		if(AssertUtils.isNotEmpty(headers)) {
			for(Entry<StringStringheader : headers.entrySet()) {
				request.addHeader(header.getKey(), header.getValue());
			}
		}
		if(AssertUtils.isNotEmpty(params)) {
			request.bodyForm(getFormParams(params));
		}
		try {
			return request.execute().webResponse();
catch(IOException e) {
			.debug("Unable to fetch repsonse from url: {}"urie);
		}
		return null;
	}

Hit the URL with given parameters and return the http response.

Parameters:
uri the url to hit
method the VERB to use
requestContentType the content type of the request body
requestBody the request body string
Returns:
the WebResponse obtained
	public static WebResponse invokeUrl(final String urifinal WebRequestMethod methodfinal String requestContentTypefinal String requestBody) {
		WebRequest request = getWebRequest(urimethod);
		request.bodyString(requestBody, ContentType.create(requestContentType));
		try {
			return request.execute().webResponse();
catch(IOException e) {
			.debug("Unable to fetch repsonse from url: {}"urie);
		}
		return null;
	}

POST the XML representation of the given object, to the given URL. The object is converted to XML format using com.thoughtworks.xstream.XStream project.

Parameters:
uri the url to hit
object the object to be sent in request body
Returns:
the WebResponse obtained
	public static WebResponse postXML(final String urifinal Object object) {
		String requestBody = XStreamUtils.getXStream(object.getClass()).toXML(object);
		request.bodyString(requestBody, ContentType.create("text/xml"));
		try {
			return request.execute().webResponse();
catch(IOException e) {
			.debug("Unable to fetch repsonse from url: {}"urie);
		}
		return null;
	}

POST the JSON representation of the given object to the given URL. The object is converted to JSON format usign com.google.gson.Gson project.

Parameters:
uri the url to hit
object the object to be sent in request body
Returns:
the WebResponse obtained
	public static WebResponse postJSON(final String urifinal Object object) {
		String requestBody = GsonUtils.getGson().toJson(object);
		request.bodyString(requestBody, ContentType.create("application/json"));
		try {
			return request.execute().webResponse();
catch(IOException e) {
			.debug("Unable to fetch repsonse from url: {}"urie);
		}
		return null;
	}

Get the WebRequest object for the given VERB method.

Parameters:
uri the url to hit
method the HTTP VERB to be used
Returns:
the WebRequest instance for the request
	public static WebRequest getWebRequest(final String urifinal WebRequestMethod method) {
		if(method == null) {
			throw new IllegalArgumentException("WebRequestMethod cannot be null");
		}
		WebRequest request = null;
		switch(method) {
			case :
				request = WebRequest.delete(uri);
				break;
			case :
				request = WebRequest.get(uri);
				break;
			case :
				request = WebRequest.head(uri);
				break;
			case :
				request = WebRequest.options(uri);
				break;
			case :
				request = WebRequest.post(uri);
				break;
			case :
				request = WebRequest.put(uri);
				break;
			case :
				request = WebRequest.trace(uri);
				break;
		}
		if(request != null) {
			return request;
		}
		throw new IllegalStateException("All options of enumeration have a check above, reaching this is impossible. This is a coding horror.");
	}

Change the default value of the connection timeout.

Parameters:
millis the timeout in millis
	public static void setConnectionTimeout(int millis) {
	}

Change the default value of the socket timeout.

Parameters:
millis the timeout in millis
	public static void setSocketTimeout(int millis) {
		 = millis;
	}

Execute the given WebRequest silently.

Parameters:
request the WebRequest to be executed
Returns:
WebResponse obtained
Throws:
java.lang.IllegalArgumentException if the WebRequest is null
	public static WebResponse executeSilently(WebRequest request) {
		if(request == null) {
			throw new IllegalArgumentException("Webrequest to be executed cannot be null");
		}
		try {
			return request.execute().webResponse();
catch(Exception e) {
			.debug("Unable to fetch repsonse from url: {}"request.getHttpRequest().getURI().toString(), e);	
		}
		return null;
	}

Create a org.apache.http.NameValuePair list from the given java.util.Map of params to be passed.

Parameters:
params the params to convert to
Returns:
a list of org.apache.http.NameValuePairs generated
	private static List<NameValuePairgetFormParams(Map<StringStringparams) {
		for(Entry<StringStringentry : params.entrySet()) {
			nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		return nvps;
	}
New to GrepCode? Check out our FAQ X