View Javadoc

1   /*******************************************************************************
2    * Copyright (c) 2007, 2014 Massimiliano Ziccardi
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *******************************************************************************/
16  package it.jnrpe.plugin.utils;
17  
18  import java.io.BufferedReader;
19  import java.io.DataOutputStream;
20  import java.io.IOException;
21  import java.io.InputStreamReader;
22  import java.net.HttpURLConnection;
23  import java.net.URL;
24  import java.util.Map.Entry;
25  import java.util.Properties;
26  
27  /**
28   * Utility class for various HTTP operations.
29   * 
30   * @author Frederico Campos
31   * 
32   */
33  public class HttpUtils {
34  
35  	/**
36  	 * Do a http get request and return response
37  	 * 
38  	 * @param url
39  	 * @param requestProps
40  	 * @param timeout
41  	 * @param includeHeaders
42  	 * @param ignoreBody
43  	 * @return
44  	 * @throws Exception
45  	 */
46  	public static String doGET(final URL url, final Properties requestProps,
47  			final Integer timeout, boolean includeHeaders, boolean ignoreBody)
48  			throws Exception {
49  		return doRequest(url, requestProps, timeout, includeHeaders,
50  				ignoreBody, "GET");
51  	}
52  
53  	/**
54  	 * Do a http head request and return response
55  	 * 
56  	 * @param url
57  	 * @param requestProps
58  	 * @param timeout
59  	 * @param includeHeaders
60  	 * @param ignoreBody
61  	 * @return
62  	 * @throws Exception
63  	 */
64  	public static String doHEAD(final URL url, final Properties requestProps,
65  			final Integer timeout, boolean includeHeaders, boolean ignoreBody)
66  			throws Exception {
67  		return doRequest(url, requestProps, timeout, includeHeaders,
68  				ignoreBody, "HEAD");
69  	}
70  
71  	/**
72  	 * Do a http post request and return response
73  	 * 
74  	 * @param url
75  	 * @param requestProps
76  	 * @param timeout
77  	 * @param encodedData
78  	 * @param includeHeaders
79  	 * @param ignoreBody
80  	 * @return
81  	 * @throws IOException
82  	 */
83  	public static String doPOST(final URL url, final Properties requestProps,
84  			final Integer timeout, final String encodedData,
85  			boolean includeHeaders, boolean ignoreBody) throws IOException {
86  		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
87  		setRequestProperties(requestProps, conn, timeout);
88  		sendPostData(conn, encodedData);
89  		return parseHttpResponse(conn, includeHeaders, ignoreBody);
90  	}
91  
92  	/**
93  	 * Submits http post data to an HttpURLConnection
94  	 * 
95  	 * @param conn
96  	 * @param encodedData
97  	 * @throws IOException
98  	 */
99  	public static void sendPostData(HttpURLConnection conn, String encodedData)
100 			throws IOException {
101 		conn.setDoOutput(true);
102 		conn.setRequestMethod("POST");
103 		if (conn.getRequestProperty("Content-Type") == null) {
104 			conn.setRequestProperty("Content-Type",
105 					"application/x-www-form-urlencoded");
106 		}
107 		if (encodedData != null) {
108 			if (conn.getRequestProperty("Content-Length") == null) {
109 				conn.setRequestProperty("Content-Length",
110 						"" + encodedData.getBytes("UTF-8").length);
111 			}
112 			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
113 			out.write(encodedData.getBytes());
114 			out.close();
115 		}
116 	}
117 
118 	private static String doRequest(final URL url,
119 			final Properties requestProps, final Integer timeout,
120 			boolean includeHeaders, boolean ignoreBody, String method)
121 			throws Exception {
122 		if (method.toUpperCase().equals("POST")) {
123 			throw new Exception(
124 					"use it.jnrpe.plugin.utils.HttpUtils.doPOST instead.");
125 		}
126 		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
127 		setRequestProperties(requestProps, conn, timeout);
128 		conn.setRequestMethod("GET");
129 		String response = parseHttpResponse(conn, includeHeaders, ignoreBody);
130 		return response;
131 	}
132 
133 	/**
134 	 * Sets request headers for an http connection
135 	 * 
136 	 * @param props
137 	 * @param conn
138 	 * @param timeout
139 	 */
140 	public static void setRequestProperties(final Properties props,
141 			HttpURLConnection conn, Integer timeout) {
142 		if (props != null) {
143 			if (props.get("User-Agent") == null) {
144 				conn.setRequestProperty("User-Agent", "Java");
145 			}
146 
147 			for (Entry entry : props.entrySet()) {
148 				conn.setRequestProperty(String.valueOf(entry.getKey()),
149 						String.valueOf(entry.getValue()));
150 			}
151 		}
152 
153 		if (timeout != null) {
154 			conn.setConnectTimeout(timeout * 1000);
155 		}
156 
157 	}
158 
159 	/**
160 	 * Parses an http request response
161 	 * 
162 	 * @param conn
163 	 * @param includeHeaders
164 	 * @param ignoreBody
165 	 * @return
166 	 * @throws IOException
167 	 */
168 	public static String parseHttpResponse(HttpURLConnection conn,
169 			boolean includeHeaders, boolean ignoreBody) throws IOException {
170 		StringBuffer buff = new StringBuffer();
171 		if (includeHeaders) {
172 			buff.append(conn.getResponseCode() + " "
173 					+ conn.getResponseMessage() + "\n");
174 			int idx = (conn.getHeaderFieldKey(0) == null) ? 1 : 0;
175 			while (true) {
176 				String key = conn.getHeaderFieldKey(idx);
177 				if (key == null) {
178 					break;
179 				}
180 				buff.append(key + ": " + conn.getHeaderField(idx) + "\n");
181 				++idx;
182 			}
183 		}
184 		if (!ignoreBody) {
185 			BufferedReader in = new BufferedReader(new InputStreamReader(
186 					conn.getInputStream()));
187 			String inputLine;
188 			while ((inputLine = in.readLine()) != null) {
189 				buff.append(inputLine);
190 			}
191 			in.close();
192 		}
193 		return buff.toString();
194 	}
195 
196 }