Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.askfast.askfastapi.util;

Author(s):
Jos de Jong, <jos@almende.org>
File:
HttpUtil.java
Brief:
HttpUtil is a single class containing methods to conveniently perform HTTP requests. HttpUtil only uses regular java io and net functionality and does not depend on external libraries. The class contains methods to perform a get, post, put, and delete request, and supports posting forms. Optionally, one can provide headers. Example usage: // get String res = HttpUtil.get("http://www.google.com"); // post String res = HttpUtil.post("http://sendmedata.com", "This is the data"); // post form Map<String, String> params = new HashMap<String, String>(); params.put("firstname", "Joe"); params.put("lastname", "Smith"); params.put("age", "28"); String res = HttpUtil.postForm("http://site.com/newuser", params); // append query parameters to url String url = "http://mydatabase.com/users"; Map<String, String> params = new HashMap<String, String>(); params.put("orderby", "name"); params.put("limit", "10"); String fullUrl = HttpUtil.appendQueryParams(url, params); // fullUrl = "http://mydatabase.com/user?orderby=name&limit=10"
License:
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. Copyright (c) 2012 Almende B.V.
Date:
2012-05-14
 
 
 import java.net.URL;
 import java.util.Map;
 
 public class HttpUtil {
Send a get request

Parameters:
url
Returns:
response
Throws:
java.io.IOException
 
 	static public String get(String urlthrows IOException {
 		return get(urlnull);
 	}

Send a get request

Parameters:
url Url as string
headers Optional map with headers
Returns:
response Response as string
Throws:
java.io.IOException
 
 	static public String get(String url,
 			Map<StringStringheadersthrows IOException {
 		return fetch("GET"urlnullheaders);
 	}

Send a post request

Parameters:
url Url as string
body Request body as string
headers Optional map with headers
Returns:
response Response as string
Throws:
java.io.IOException
 
 	static public String post(String urlString body,
 			Map<StringStringheadersthrows IOException {
 		return fetch("POST"urlbodyheaders);
 	}

Send a post request

Parameters:
url Url as string
body Request body as string
Returns:
response Response as string
Throws:
java.io.IOException
	static public String post(String urlString bodythrows IOException {
		return post(urlbodynull);
	}

Post a form with parameters

Parameters:
url Url as string
params map with parameters/values
Returns:
response Response as string
Throws:
java.io.IOException
	static public String postForm(String urlMap<StringStringparams
			throws IOException {
		return postForm(urlparamsnull);
	}

Post a form with parameters

Parameters:
url Url as string
params Map with parameters/values
headers Optional map with headers
Returns:
response Response as string
Throws:
java.io.IOException
	static public String postForm(String urlMap<StringStringparams,
			Map<StringStringheadersthrows IOException {
		// set content type
		if (headers == null) {
			headers = new HashMap<StringString>();
		}
		headers.put("Content-Type""application/x-www-form-urlencoded");
		// parse parameters
		String body = "";
		if (params != null) {
			boolean first = true;
			for (String param : params.keySet()) {
				if (first) {
					first = false;
				}
				else {
					body += "&";
				}
				String value = params.get(param);
				body += URLEncoder.encode(param"UTF-8") + "=";
				body += URLEncoder.encode(value"UTF-8");
			}
		}
		return post(urlbodyheaders);
	}

Send a put request

Parameters:
url Url as string
body Request body as string
headers Optional map with headers
Returns:
response Response as string
Throws:
java.io.IOException
	static public String put(String urlString body,
			Map<StringStringheadersthrows IOException {
		return fetch("PUT"urlbodyheaders);
	}

Send a put request

Parameters:
url Url as string
Returns:
response Response as string
Throws:
java.io.IOException
	static public String put(String urlString bodythrows IOException {
		return put(urlbodynull);
	}

Send a delete request

Parameters:
url Url as string
headers Optional map with headers
Returns:
response Response as string
Throws:
java.io.IOException
	static public String delete(String url,
			Map<StringStringheadersthrows IOException {
		return fetch("DELETE"urlnullheaders);
	}

Send a delete request

Parameters:
url Url as string
Returns:
response Response as string
Throws:
java.io.IOException
	static public String delete(String urlthrows IOException {
		return delete(urlnull);
	}

Append query parameters to given url

Parameters:
url Url as string
params Map with query parameters
Returns:
url Url with query parameters appended
Throws:
java.io.IOException
	static public String appendQueryParams(String url
			Map<StringStringparamsthrows IOException {
		String fullUrl = new String(url);
		if (params != null) {
			boolean first = (fullUrl.indexOf('?') == -1);
			for (String param : params.keySet()) {
				if (first) {
					fullUrl += '?';
					first = false;
				}
				else {
					fullUrl += '&';
				}
				String value = params.get(param);
				fullUrl += URLEncoder.encode(param"UTF-8") + '=';
				fullUrl += URLEncoder.encode(value"UTF-8");
			}
		}
		return fullUrl;
	}

Retrieve the query parameters from given url

Parameters:
url Url containing query parameters
Returns:
params Map with query parameters
Throws:
java.io.IOException
	static public Map<StringStringgetQueryParams(String url
			throws IOException {
		Map<StringStringparams = new HashMap<StringString>();
		int start = url.indexOf('?');
		while (start != -1) {
			// read parameter name
			int equals = url.indexOf('='start);
			String param = "";
			if (equals != -1) {
				param = url.substring(start + 1, equals);
			}
			else {
				param = url.substring(start + 1);
			}
			// read parameter value
			String value = "";
			if (equals != -1) {
				start = url.indexOf('&'equals);
				if (start != -1) {
					value = url.substring(equals + 1, start);
				}
				else {
					value = url.substring(equals + 1);
				}
			}
			params.put(URLDecoder.decode(param"UTF-8"), 
				URLDecoder.decode(value"UTF-8"));
		}
		return params;
	}

Returns the url without query parameters

Parameters:
url Url containing query parameters
Returns:
url Url without query parameters
Throws:
java.io.IOException
	static public String removeQueryParams(String url
			throws IOException {
		int q = url.indexOf('?');
		if (q != -1) {
			return url.substring(0, q);
		}
		else {
			return url;
		}
	}

Send a request

Parameters:
method HTTP method, for example "GET" or "POST"
url Url as string
body Request body as string
headers Optional map with headers
Returns:
response Response as string
Throws:
java.io.IOException
	static public String fetch(String methodString urlString body,
			Map<StringStringheadersthrows IOException {
		// connection
		URL u = new URL(url);
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(30000);
		// method
		if (method != null) {
			conn.setRequestMethod(method);
		}
		// headers
		if (headers != null) {
			for(String key : headers.keySet()) {
				conn.addRequestProperty(keyheaders.get(key));
			}
		}
		// body
		if (body != null) {
			conn.setDoOutput(true);
			os.write(body.getBytes());
			os.flush();
			os.close();
		}
		// response
		String response = streamToString(is);
		is.close();
		// handle redirects
		if (conn.getResponseCode() == 301) {
			String location = conn.getHeaderField("Location");
			return fetch(methodlocationbodyheaders);
		}
		return response;
	}

Read an input stream into a string

Parameters:
in
Returns:
Throws:
java.io.IOException
	static public String streamToString(InputStream inthrows IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}
New to GrepCode? Check out our FAQ X