List of usage examples for org.apache.commons.httpclient HttpException getMessage
public String getMessage()
From source file:org.medici.bia.controller.manuscriptviewer.ReverseProxyIIPImageThumbnailController.java
/** * // w w w . j a va 2 s.co m * * @param volumeId * @return */ @RequestMapping(method = RequestMethod.GET) public void reverseProxyIIPImage(HttpServletRequest httpServletRequest, HttpServletResponse response) { // Create an instance of HttpClient. HttpClient client = new HttpClient(); StringBuilder stringBuilder = new StringBuilder(""); stringBuilder.append(properties.getProperty("iipimage.protocol")); stringBuilder.append("://"); stringBuilder.append(properties.getProperty("iipimage.host")); stringBuilder.append(':'); stringBuilder.append(properties.getProperty("iipimage.port")); stringBuilder.append(properties.getProperty("iipimage.fcgi.path")); stringBuilder.append('?'); stringBuilder.append("WID=120&"); stringBuilder.append("FIF="); stringBuilder.append(properties.getProperty("iipimage.image.path")); stringBuilder.append(httpServletRequest.getParameter("imageName")); stringBuilder.append("&CVT=JPEG"); // Create a method instance. GetMethod method = new GetMethod(stringBuilder.toString()); try { // Execute the method. client.executeMethod(method); logger.debug("Reverse Proxying IIPImageThumbnail Url : " + stringBuilder.toString() + " (Status Line" + method.getStatusLine() + ")"); // Set content type response.setContentType(method.getResponseHeader("Content-Type").getValue()); IOUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream()); // Flushing request response.getOutputStream().flush(); } catch (HttpException httpException) { logger.error("Fatal protocol violation: " + httpException.getMessage()); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } }
From source file:org.mitre.mat.engineclient.MATCgiClient.java
protected JsonNode postHTTP(ArrayList<NameValuePair> pArrayList, HashMap<String, String> data) throws MATEngineClientException { // Serialize the document, send it to HTTP, deserialize. if (data != null) { int mapsize = data.size(); Iterator keyValuePairs1 = data.entrySet().iterator(); for (int i = 0; i < mapsize; i++) { Map.Entry entry = (Map.Entry) keyValuePairs1.next(); Object key = entry.getKey(); Object value = entry.getValue(); pArrayList.add(new NameValuePair((String) key, (String) value)); }//w w w. ja v a 2 s . c om } NameValuePair[] pArray = (NameValuePair[]) pArrayList.toArray(new NameValuePair[1]); HttpClientParams params = new HttpClientParams(); params.setContentCharset("utf-8"); HttpClient client = new HttpClient(params); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); method.setRequestBody(pArray); String resString = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new MATEngineClientException("HTTP method failed: " + method.getStatusLine()); } BufferedReader b = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "utf-8")); StringBuffer buf = new StringBuffer(); int READ_LEN = 2048; char[] cbuf = new char[READ_LEN]; while (true) { int chars = b.read(cbuf, 0, READ_LEN); if (chars < 0) { break; } // You may not read READ_LEN chars, but // that doesn't mean you're done. buf.append(cbuf, 0, chars); } resString = new String(buf); } catch (HttpException e) { throw new MATEngineClientException("Fatal protocol violation: " + e.getMessage()); } catch (IOException e) { throw new MATEngineClientException("Fatal transport error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } JsonNode responseObj = null; JsonFactory jsonFact = new JsonFactory(); JsonNode jsonValues; JsonParser parser; try { parser = jsonFact.createJsonParser(new StringReader(resString)); return new ObjectMapper().readTree(parser); } catch (org.codehaus.jackson.JsonParseException ex) { Logger.getLogger(MATCgiClient.class.getName()).log(Level.SEVERE, null, ex); throw new MATEngineClientException("Couldn't digest the following string as JSON: " + resString); } catch (IOException ex) { Logger.getLogger(MATCgiClient.class.getName()).log(Level.SEVERE, null, ex); throw new MATEngineClientException("Couldn't interpret response document: " + ex.getMessage()); } }
From source file:org.mskcc.pathdb.task.ImportExternalDbTask.java
private void checkUrl(ExternalDatabaseRecord dbRecord, ProgressMonitor pMonitor) { try {// ww w . java 2 s . c o m int statusCode = ExternalDbLinkTester.checkSampleLink(dbRecord); pMonitor.setCurrentMessage( "--> Response: " + statusCode + ", " + HttpStatus.getStatusText(statusCode) + "\n"); if (statusCode != HttpStatus.SC_OK) { pMonitor.setCurrentMessage(WARNING_MSG); } } catch (HttpException e) { pMonitor.setCurrentMessage( WARNING_MSG + " Error Message: " + e.getReasonCode() + ", " + e.getReason()); } catch (IOException e) { pMonitor.setCurrentMessage(WARNING_MSG + " Error Message: " + e.getMessage()); } }
From source file:org.openhab.binding.km200.internal.KM200Comm.java
/** * This function does the GET http communication to the device * *//*w w w. j a v a 2 s . com*/ public byte[] getDataFromService(String service) { byte[] responseBodyB64 = null; int maxNbrGets = 3; int statusCode = 0; // Create an instance of HttpClient. if (client == null) { client = new HttpClient(); } synchronized (client) { // Create a method instance. GetMethod method = new GetMethod("http://" + device.getIP4Address() + service); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Set the right header method.setRequestHeader("Accept", "application/json"); method.addRequestHeader("User-Agent", "TeleHeater/2.2.3"); try { for (int i = 0; i < maxNbrGets && statusCode != HttpStatus.SC_OK; i++) { // Execute the method. statusCode = client.executeMethod(method); // Check the status switch (statusCode) { case HttpStatus.SC_OK: break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: /* Unknown problem with the device, wait and try again */ logger.warn("HTTP GET failed: 500, internal server error, repeating.. "); Thread.sleep(2000L); continue; case HttpStatus.SC_FORBIDDEN: /* Service is available but not readable */ byte[] test = new byte[1]; return test; default: logger.error("HTTP GET failed: {}", method.getStatusLine()); return null; } } device.setCharSet(method.getResponseCharSet()); // Read the response body. responseBodyB64 = ByteStreams.toByteArray(method.getResponseBodyAsStream()); } catch (HttpException e) { logger.error("Fatal protocol violation: {}", e.getMessage()); } catch (InterruptedException e) { logger.error("Sleep was interrupted: {}", e.getMessage()); } catch (IOException e) { logger.error("Fatal transport error: {}", e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return responseBodyB64; } }
From source file:org.panlab.software.fci.uop.UoPGWClient.java
/** * It makes a POST towards the gateway//w w w . j a v a 2s .co m * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; System.out.println("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = uopGWAddress + "/" + ptm + "/" + resourceInstance; System.out.println("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // System.out.println("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:org.panlab.software.fci.uop.UoPGWClient.java
/** * It makes a GET towards the gateway. The response is retrieved with the {@link PanlabGWClient#getResponse_stream()} ; * @author ctranoris/* w w w .ja va2 s.com*/ * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the resource Instance, e.g.: uop * @see PanlabGWClient#getResponse_stream() */ public void GETexecute(String resourceInstance, String ptmAlias) { HttpClient client = new HttpClient(); // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = uopGWAddress + "/" + ptm + "/" + resourceInstance; System.out.println("Request: " + url); // Create a method instance. GetMethod get = new GetMethod(url); get.setRequestHeader("User-Agent", userAgent); get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); try { // execute the GET client.executeMethod(get); // print the status and response InputStream responseBody = get.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // release any connection resources used by the method get.releaseConnection(); } }
From source file:org.panlab.software.fci.uop.UoPGWClient.java
/** * It makes a DELETE towards the gateway * @author ctranoris/*from w w w . j a v a2 s .c o m*/ * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public void DELETEexecute(String resourceInstance, String ptmAlias, String content) { System.out.println("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = uopGWAddress + "/" + ptm + "/" + resourceInstance; System.out.println("Request: " + url); // Create a method instance. DeleteMethod delMethod = new DeleteMethod(url); delMethod.setRequestHeader("User-Agent", userAgent); delMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary // delMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, // new DefaultHttpMethodRetryHandler(3, false)); // RequestEntity requestEntity = null; // try { // requestEntity = new StringRequestEntity(tgwcontent, // "application/x-www-form-urlencoded", "utf-8"); // } catch (UnsupportedEncodingException e1) { // e1.printStackTrace(); // } //delMethod.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(delMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + delMethod.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = delMethod.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // System.out.println("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. delMethod.releaseConnection(); } }
From source file:org.purl.sword.client.Client.java
/** * Retrieve the service document. The service document is located at the * specified URL. This calls getServiceDocument(url,onBehalfOf). * /*from w ww. j av a 2 s . c o m*/ * @param url * The location of the service document. * @return The ServiceDocument, or <code>null</code> if there was a * problem accessing the document. e.g. invalid access. * * @throws SWORDClientException * If there is an error accessing the resource. */ public ServiceDocument getServiceDocument(String url, String onBehalfOf) throws SWORDClientException { URL serviceDocURL = null; try { serviceDocURL = new URL(url); } catch (MalformedURLException e) { // Try relative URL URL baseURL = null; try { baseURL = new URL("http", server, Integer.valueOf(port), "/"); serviceDocURL = new URL(baseURL, (url == null) ? "" : url); } catch (MalformedURLException e1) { // No dice, can't even form base URL... throw new SWORDClientException(url + " is not a valid URL (" + e1.getMessage() + "), and could not form a relative one from: " + baseURL + " / " + url, e1); } } GetMethod httpget = new GetMethod(serviceDocURL.toExternalForm()); if (doAuthentication) { // this does not perform any check on the username password. It // relies on the server to determine if the values are correct. setBasicCredentials(username, password); httpget.setDoAuthentication(true); } Properties properties = new Properties(); if (containsValue(onBehalfOf)) { log.debug("Setting on-behalf-of: " + onBehalfOf); httpget.addRequestHeader(new Header(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf)); properties.put(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf); } if (containsValue(userAgent)) { log.debug("Setting userAgent: " + userAgent); httpget.addRequestHeader(new Header(HttpHeaders.USER_AGENT, userAgent)); properties.put(HttpHeaders.USER_AGENT, userAgent); } ServiceDocument doc = null; try { client.executeMethod(httpget); // store the status code status = new Status(httpget.getStatusCode(), httpget.getStatusText()); if (status.getCode() == HttpStatus.SC_OK) { String message = readResponse(httpget.getResponseBodyAsStream()); log.debug("returned message is: " + message); doc = new ServiceDocument(); lastUnmarshallInfo = doc.unmarshall(message, properties); } else { throw new SWORDClientException("Received error from service document request: " + status); } } catch (HttpException ex) { throw new SWORDClientException(ex.getMessage(), ex); } catch (IOException ioex) { throw new SWORDClientException(ioex.getMessage(), ioex); } catch (UnmarshallException uex) { throw new SWORDClientException(uex.getMessage(), uex); } finally { httpget.releaseConnection(); } return doc; }
From source file:org.purl.sword.client.Client.java
/** * Post a file to the server. The different elements of the post are encoded * in the specified message./*from www . java2 s . c o m*/ * * @param message * The message that contains the post information. * * @throws SWORDClientException * if there is an error during the post operation. */ public DepositResponse postFile(PostMessage message) throws SWORDClientException { if (message == null) { throw new SWORDClientException("Message cannot be null."); } PostMethod httppost = new PostMethod(message.getDestination()); if (doAuthentication) { setBasicCredentials(username, password); httppost.setDoAuthentication(true); } DepositResponse response = null; String messageBody = ""; try { if (message.isUseMD5()) { String md5 = ChecksumUtils.generateMD5(message.getFilepath()); if (message.getChecksumError()) { md5 = "1234567890"; } log.debug("checksum error is: " + md5); if (md5 != null) { httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_MD5, md5)); } } String filename = message.getFilename(); if (!"".equals(filename)) { httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_DISPOSITION, " filename=" + filename)); } if (containsValue(message.getSlug())) { httppost.addRequestHeader(new Header(HttpHeaders.SLUG, message.getSlug())); } if (message.getCorruptRequest()) { // insert a header with an invalid boolean value httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, "Wibble")); } else { httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, Boolean.toString(message.isNoOp()))); } httppost.addRequestHeader(new Header(HttpHeaders.X_VERBOSE, Boolean.toString(message.isVerbose()))); String packaging = message.getPackaging(); if (packaging != null && packaging.length() > 0) { httppost.addRequestHeader(new Header(HttpHeaders.X_PACKAGING, packaging)); } String onBehalfOf = message.getOnBehalfOf(); if (containsValue(onBehalfOf)) { httppost.addRequestHeader(new Header(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf)); } String userAgent = message.getUserAgent(); if (containsValue(userAgent)) { httppost.addRequestHeader(new Header(HttpHeaders.USER_AGENT, userAgent)); } FileRequestEntity requestEntity = new FileRequestEntity(new File(message.getFilepath()), message.getFiletype()); httppost.setRequestEntity(requestEntity); client.executeMethod(httppost); status = new Status(httppost.getStatusCode(), httppost.getStatusText()); log.info("Checking the status code: " + status.getCode()); if (status.getCode() == HttpStatus.SC_ACCEPTED || status.getCode() == HttpStatus.SC_CREATED) { messageBody = readResponse(httppost.getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.setLocation(httppost.getResponseHeader("Location").getValue()); // added call for the status code. lastUnmarshallInfo = response.unmarshall(messageBody, new Properties()); } else { messageBody = readResponse(httppost.getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.unmarshallErrorDocument(messageBody); } return response; } catch (NoSuchAlgorithmException nex) { throw new SWORDClientException("Unable to use MD5. " + nex.getMessage(), nex); } catch (HttpException ex) { throw new SWORDClientException(ex.getMessage(), ex); } catch (IOException ioex) { throw new SWORDClientException(ioex.getMessage(), ioex); } catch (UnmarshallException uex) { throw new SWORDClientException(uex.getMessage() + "(<pre>" + messageBody + "</pre>)", uex); } finally { httppost.releaseConnection(); } }
From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java
/** * Fire off a request to a URL using the specified method but reuse the client for efficiency, * include optional params and data in the request, * the response data will be returned in the object if the request can be carried out * //from www . j a va 2 s. co m * @param httpClientWrapper (optional) allows the http client to be reused for efficiency, * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to * create a reusable instance * @param URL the url to send the request to (absolute or relative, can include query params) * @param method the method to use (e.g. GET, POST, etc.) * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method * @param params (optional) headers to send along with the request, will be encoded in the headers * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work, * otherwise https requests will fail if the certs cannot be centrally verified * @return an object representing the response, includes data about the response * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable) */ @SuppressWarnings("deprecation") public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method, Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) { if (guaranteeSSL) { // added this to attempt to force the SSL self signed certs to work Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); } if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) { httpClientWrapper = makeReusableHttpClient(false, 0, null); } HttpMethod httpMethod = null; if (method.equals(Method.GET)) { GetMethod gm = new GetMethod(URL); // put params into query string gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params)); // warn about data being set if (data != null) { System.out.println( "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)"); } gm.setFollowRedirects(true); httpMethod = gm; } else if (method.equals(Method.POST)) { PostMethod pm = new PostMethod(URL); // special handling for post params if (params != null) { for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { System.out.println("WARN: null value supplied for param name (" + entry.getKey() + ") or value (" + entry.getValue() + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)"); } pm.addParameter(entry.getKey(), entry.getValue()); } } // handle data handleRequestData(pm, data); httpMethod = pm; } else if (method.equals(Method.PUT)) { PutMethod pm = new PutMethod(URL); // put params into query string pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params)); // handle data handleRequestData(pm, data); httpMethod = pm; } else if (method.equals(Method.DELETE)) { DeleteMethod dm = new DeleteMethod(URL); // put params into query string dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params)); // warn about data being set if (data != null) { System.out.println( "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)"); } httpMethod = dm; } else { throw new IllegalArgumentException("Cannot handle method: " + method); } // set the headers for the request if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { httpMethod.addRequestHeader(entry.getKey(), entry.getValue()); } } HttpResponse response = null; try { int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod); response = new HttpResponse(responseCode); // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405 InputStream is = httpMethod.getResponseBodyAsStream(); StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = is.read(b)) != -1;) { out.append(new String(b, 0, n)); if (out.length() > MAX_RESPONSE_SIZE_CHARS) { // die if the response exceeds the maximum chars allowed throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS + " chars) while processing the response"); } } String body = out.toString(); //String body = httpMethod.getResponseBodyAsString(); // byte[] responseBody = httpMethod.getResponseBody(); // if (responseBody != null) { // body = new String(responseBody, "UTF-8"); // } response.setResponseBody(body); response.setResponseMessage(httpMethod.getStatusText()); // now get the headers HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>(); Header[] respHeaders = httpMethod.getResponseHeaders(); for (int i = 0; i < respHeaders.length; i++) { Header header = respHeaders[i]; // now we convert the headers from these odd pairs into something more like servlets expect HeaderElement[] elements = header.getElements(); if (elements == null || elements.length == 0) { continue; } else if (elements.length >= 1) { String[] values = new String[elements.length]; StringBuilder sb = new StringBuilder(); for (int j = 0; j < elements.length; j++) { sb.setLength(0); // clear the StringBuilder sb.append(elements[j].getName()); if (elements[j].getValue() != null) { sb.append("="); sb.append(elements[j].getValue()); } values[j] = sb.toString(); } responseHeaders.put(header.getName(), values); } } response.setResponseHeaders(responseHeaders); } catch (HttpException he) { // error contained in he.getMessage() throw new HttpRequestException( "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL + ") using method (" + method + ") :: " + he.getMessage(), he); } catch (IOException ioe) { // other exception throw new HttpIOException( "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url (" + URL + ") using method (" + method + ") :: " + ioe.getMessage(), ioe); } finally { httpMethod.releaseConnection(); } return response; }