Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.tectonica.util;
  
  import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
General HTTP utility class for invoking HTTP requests using only Java's standard network packages (in particular, avoiding Apache Commons HttpClient). The class offers a single static method execute(java.lang.String,java.lang.String,java.lang.String,com.tectonica.util.HTTP.Headers,com.tectonica.util.HTTP.Attachment,com.tectonica.util.HTTP.CookieStore), or, for better convenience, a builder pattern, accessible via url(java.lang.String)

Author(s):
Zach Melamed
 
 public class HTTP
 {
 	public static class HttpResponse
 	{
 		public final int statusCode;
 		public final String content;
 		public final Map<StringList<String>> headers;
 		public final long latency;
 
 		public HttpResponse(int statusCodeString contentMap<StringList<String>> headerslong latency)
 		{
 			this. = statusCode;
 			this. = content;
 			this. = headers;
 			this. = latency;
 		}
 
 		public String toString()
 		{
 			return "(HTTP " +  + "): [" +  + "]\n" + .toString();
 		}
 	}
 
 	public static class Headers implements Iterable<Entry<StringString>>
 	{
 		private Map<StringStringheaders = new LinkedHashMap<>();
 
 		public void add(String headerNameString headerValueboolean exclusive)
 		{
 			String value = .get(headerName);
 			if (value == null || exclusive)
 				value = headerValue;
 			else
 				value += ", " + headerValue;
 			.put(headerNamevalue);
 		}
 
 		{
 			return .entrySet().iterator();
 		}
 	}
 
 	public static class Attachment
 	{
 		public final String fieldName;
 		public final String fileName;
 		public final File file;
 		public final InputStream is;
 
 		public Attachment(File fileString fieldName)
 		{
 			this. = fieldName;
 			this. = file;
 			this. = file.getName();
 			this. = null;
 		}
 
 		public Attachment(InputStream isString fieldNameString fileName)
 		{
 			this. = fieldName;
 			this. = null;
 			this. = fileName;
 			this. = is;
 		}
 
		{
			if ( != null)
				return ;
			try
			{
				return new FileInputStream();
			}
			catch (IOException e)
			{
				throw new RuntimeException(e);
			}
		}
	}
	public static class CookieStore
	{
		private Map<StringStringcookies = new HashMap<StringString>();
		private void fromHeader(List<StringsetCookies)
		{
			if (setCookies != null && !setCookies.isEmpty())
			{
				for (String cookie : setCookies)
				{
					String[] kv = cookie.split(";")[0].trim().split("=");
					if (kv[1].isEmpty())
					else
						.put(kv[0], kv[1]);
				}
			}
		}
		private String toHeader()
		{
			if (isEmpty())
				return null;
			boolean first = true;
			for (Iterator<Entry<StringString>> iter = .entrySet().iterator(); iter.hasNext();)
			{
				Entry<StringStringkv = iter.next();
				if (first)
					first = false;
				else
					sb.append(",");
				sb.append(kv.getKey()).append("=").append(kv.getValue());
			}
			return sb.toString();
		}
		public boolean isEmpty()
		{
			return .isEmpty();
		}
	}
	private static final String CRLF = "\r\n";
	private static final String HYPHENS = "--";
	private static final String BOUNDARY = "*************";
	public static HttpResponse execute(String methodString urlString bodyHeaders headersAttachment attachmentCookieStore cs)
	{
		HttpURLConnection conn = null;
		try
		{
			boolean sendText = (body != null && !body.isEmpty());
			boolean sendMultipart = !sendText && (attachment != null);
			long timeBefore = System.currentTimeMillis();
			conn = (HttpURLConnection) (new URL(url)).openConnection();
			conn.setUseCaches(false);
			conn.setDoInput(true);
			conn.setDoOutput(sendText || sendMultipart);
			conn.setRequestMethod(method);
			for (Entry<StringStringheader : headers)
				conn.setRequestProperty(header.getKey(), header.getValue());
			if (cs != null && !cs.isEmpty())
				conn.setRequestProperty("Cookie"cs.toHeader());
//			conn.setRequestProperty("Connection", "Keep-Alive");
//			conn.setRequestProperty("Cache-Control", "no-cache");
			// send the request's body
			if (sendText)
			{
				byte[] requestContent = body.getBytes();
				conn.setRequestProperty("Content-Length""" + requestContent.length);
				out.write(requestContent);
				out.close();
			}
			else if (sendMultipart)
			{
				conn.setRequestProperty("Content-Type""multipart/form-data;boundary=" + );
				writeFile(attachment.getStream(), attachment.fieldNameattachment.fileNameout); // can be re-iterated with other files
				out.flush();
				out.close();
			}
//			conn.connect(); // redundant, just clearer
			Map<StringList<String>> responseHeaders = conn.getHeaderFields();
			if (cs != null)
				cs.fromHeader(responseHeaders.get("Set-Cookie"));
			// get the response
			int statusCode = conn.getResponseCode();
			InputStream is = (statusCode / 100 == 2) ? conn.getInputStream() : conn.getErrorStream();
//			conn.disconnect();
			// remove the trailing NL
			String content = (is == null) ? "" : streamToContent(is);
			long latency = System.currentTimeMillis() - timeBefore;
			return new HttpResponse(statusCodecontentresponseHeaderslatency);
		}
		catch (Exception e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
			if (conn != null)
				conn.disconnect();
		}
	}
	public static String urlEncoded(String url)
	{
		try
		{
			return URLEncoder.encode(url"UTF-8").replace("+""%20");
		}
		{
			return null// never happens as "UTF-8" is always a valid encoding
		}
	}
	private static String streamToContent(InputStream isthrows IOException
	{
		StringBuffer sb = new StringBuffer();
		String line;
		while ((line = in.readLine()) != null)
			sb.append(line).append("\n");
		in.close();
		return (sb.length() == 0) ? "" : sb.substring(0, sb.length() - "\n".length());
	}
	private static void writeFile(InputStream isString fieldNameString fileNameDataOutputStream outthrows IOException,
	{
		out.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + fileName + "\"" + );
		byte[] buffer = new byte[8192];
		int bytesRead = -1;
		while ((bytesRead = is.read(buffer)) != -1)
			out.write(buffer, 0, bytesRead);
		out.flush();
		is.close();
	}
	// /////////////////////////////////////////////////////////////////////////////////
	//
	// BUILDER API
	//
	// /////////////////////////////////////////////////////////////////////////////////
	private final String url;
	private String body = null;
	private Attachment attachment = null;
	private CookieStore cookieStore = null;
	private Headers headers = new Headers();
	public static HTTP url(String url)
	{
		return new HTTP(url);
	}
	public static HTTP url(String urlboolean encodeUrl)
	{
		return new HTTP(urlEncoded(url));
	}
	private HTTP(String url)
	{
		this. = url;
	}
	public HTTP body(String body)
	{
		this. = body;
		return this;
	}
	public HTTP contentType(String contentTypeHeader)
	{
		return header("Content-Type"contentTypeHeadertrue);
	}
	public HTTP accept(String acceptHeader)
	{
		return header("Accept"acceptHeaderfalse);
	}
	public HTTP basicAuthorization(String usernameString password)
	{
		String login = username + ":" + password;
		String encodedLogin = DatatypeConverter.printBase64Binary(login.getBytes());
		return header("Authorization""Basic " + encodedLogintrue);
	}
	public HTTP header(String headerNameString headerValue)
	{
		return header(headerNameheaderValuefalse);
	}
	public HTTP header(String headerNameString headerValueboolean exclusive)
	{
		.add(headerNameheaderValueexclusive);
		return this;
	}
	public HTTP cookieStore(CookieStore cookieStore)
	{
		this. = cookieStore;
		return this;
	}
	public HTTP attach(Attachment attachment)
	{
		this. = attachment;
		return this;
	}
	// //////////////////////////////////////////////////////////////////////////////////
	private HttpResponse execute(String method)
	{
		return execute(method);
	}
	public HttpResponse GET()
	{
		return execute("GET");
	}
	public HttpResponse POST()
	{
		return execute("POST");
	}
	public HttpResponse PUT()
	{
		return execute("PUT");
	}
	{
		return execute("DELETE");
	}
New to GrepCode? Check out our FAQ X