private String signedRequest(
      final Map<String, String> paramMap,
      final Map<String, String> cookieMap,
      final Map<String, String> headerMap,
      final String apiPath)
      throws IOException, ForbiddenException {
    final String sessionId = cookieMap.get(SessionAttributeKeys.SESSION_ID);
    if (StringUtils.isBlank(sessionId)) {
      m_log.error(SessionAttributeKeys.SESSION_ID + " not in cookies: " + cookieMap);
      throw new IOException("Missing session ID");
    }

    final String userId = cookieMap.get(SessionAttributeKeys.USER_ID);
    if (StringUtils.isBlank(userId)) {
      m_log.debug("No user ID!!");
      // throw new IOException("Blank user ID");
    } else {
      paramMap.put("userId", userId);
    }

    m_log.debug("Sending session ID as cookie: " + sessionId);

    final String baseUrl = createBaseUrl(apiPath);
    final String finalUrl = sign(baseUrl, paramMap, cookieMap);

    final HttpMethod method = new PostMethod(finalUrl);
    method.setRequestHeader("Cookie", SessionAttributeKeys.SESSION_ID + "=" + sessionId);
    if (headerMap.containsKey("Referer")) {
      method.setRequestHeader("Referer", headerMap.get("Referer"));
    }

    m_log.debug("Sending request to: {}", finalUrl);
    return post(method);
  }
Example #2
0
  /**
   * 发送http请求,并返回响应的xml报文 <功能详细描述>
   *
   * @param url http请求url
   * @param xml 请求xml报文
   * @return
   */
  private String send(HttpMethod httpMethod) {
    // 获取响应报文
    String response = null;
    int resultCode = HttpStatus.SC_OK;
    try {
      // 设置header信息,传输XML格式的
      httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_UTF_8);

      // 处理响应结果码
      resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        }
      } else {
        response = resultCode + "";
        LogUtil.error("Http response: " + httpMethod.getResponseBodyAsString());
      }
    } catch (Exception ex) {
      response = ex.toString();
      LogUtil.error("send http request error!", ex);
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }
    return response;
  }
Example #3
0
 /**
  * Retreives all of the headers from the servlet request and sets them on the proxy request
  *
  * @param httpServletRequest The request object representing the client's request to the servlet
  *     engine
  * @param httpMethodProxyRequest The request that we are about to send to the proxy host
  */
 @SuppressWarnings("unchecked")
 private void setProxyRequestHeaders(
     HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
   // Get an Enumeration of all of the header names sent by the client
   Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
   while (enumerationOfHeaderNames.hasMoreElements()) {
     String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();
     if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) continue;
     // As per the Java Servlet API 2.5 documentation:
     //		Some headers, such as Accept-Language can be sent by clients
     //		as several headers each with a different value rather than
     //		sending the header as a comma separated list.
     // Thus, we get an Enumeration of the header values sent by the client
     Enumeration enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
     while (enumerationOfHeaderValues.hasMoreElements()) {
       String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement();
       // In case the proxy host is running multiple virtual servers,
       // rewrite the Host header to ensure that we get content from
       // the correct virtual server
       if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) {
         stringHeaderValue = getProxyHostAndPort();
       }
       Header header = new Header(stringHeaderName, stringHeaderValue);
       // Set the same header on the proxy request
       httpMethodProxyRequest.setRequestHeader(header);
     }
   }
 }
Example #4
0
  private String sendApp(HttpMethod httpMethod) {

    String response = null;
    int resultCode = HttpStatus.SC_OK;

    try {

      httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_APP);

      resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        }
      } else {
        response = "ResultCode = " + resultCode;
      }
    } catch (Exception ex) {
      response = ex.toString();
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }
    return response;
  }
 /**
  * If a 'Proxy-Connection' header has been added to the request, it'll be of a 'keep-alive' type.
  * Until we support 'keep-alives', override the Proxy-Connection setting and instead pass a
  * 'close' (Otherwise every request has to timeout before we notice end-of-document).
  *
  * @param method Method to find proxy-connection header in.
  */
 public void handleAddProxyConnectionHeader(HttpMethod method) {
   Header h = method.getRequestHeader("Proxy-Connection");
   if (h != null) {
     h.setValue("close");
     method.setRequestHeader(h);
   }
 }
 private void writeOutBoundHeaders(MultivaluedMap<String, Object> metadata, HttpMethod method) {
   for (Map.Entry<String, List<Object>> e : metadata.entrySet()) {
     List<Object> vs = e.getValue();
     if (vs.size() == 1) {
       method.setRequestHeader(e.getKey(), headerValueToString(vs.get(0)));
     } else {
       StringBuilder b = new StringBuilder();
       for (Object v : e.getValue()) {
         if (b.length() > 0) {
           b.append(',');
         }
         b.append(headerValueToString(v));
       }
       method.setRequestHeader(e.getKey(), b.toString());
     }
   }
 }
Example #7
0
  /**
   * Gets the result of the execution of a get request. the attempt will be repeated until obtain
   * the exepected result
   *
   * @param path the path on which the request should be executed
   * @param expression the result that should be returned by the GET request, which allows to know
   *     if that request is completely processed or not
   * @throws Exception if something's going wrong...
   */
  public void retryGetRequestUntilObtainExpectedResponse(
      @NonNull String path, @NonNull String expression) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;
    log.debug("Sending GET request to " + fullpath + " with several attemps");

    final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY));
    final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY));

    final HttpMethod method = new GetMethod(fullpath);
    try {
      for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

      String responseAsString = null;
      String toCheck = null;
      String expected = expression;
      String prop = null;
      final int idx = expression.indexOf("=");
      if (idx > 0) {
        prop = expression.substring(0, idx);
        expected = expression.substring(idx + 1);
      }
      int statusCode;
      int attempts = 0;
      boolean success = false;
      do {
        // waiting timeToWait seconds
        Thread.sleep(timeToWait * 1000);
        statusCode = httpClient.executeMethod(method);
        attempts++;
        if (statusCode == HttpStatus.SC_OK) {
          responseAsString = method.getResponseBodyAsString();
          toCheck = responseAsString;
          if (prop != null) toCheck = JSONHelper.getPropertyValue(responseAsString, prop);
          if (toCheck.contains(expected)) {
            success = true;
            log.debug("The result is available! ");
          } else
            log.warn("The result is not yet available! | Waiting " + timeToWait + " seconds ...");
        } else
          log.warn(
              "unsuccessful GET request : "
                  + method.getStatusLine()
                  + " | Waiting "
                  + timeToWait
                  + " seconds ...");
      } while (!success && maxAttempts > attempts);
      response = new ResponseWrapper(responseAsString, statusCode);
    } catch (final Exception e) {
      log.error(e.getMessage(), e);
      throw e;
    } finally {
      method.releaseConnection();
    }
  }
 public HttpMethod generateRequestFor(List<String> recipients, String message) {
   HttpMethod httpMethod;
   if (HttpMethodType.POST.equals(outgoing.getRequest().getType())) {
     httpMethod = new PostMethod(outgoing.getRequest().getUrlPath());
     httpMethod.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE);
     addBodyParameters((PostMethod) httpMethod, recipients, message);
   } else {
     httpMethod = new GetMethod(outgoing.getRequest().getUrlPath());
   }
   httpMethod.setQueryString(addQueryParameters(recipients, message));
   return httpMethod;
 }
Example #9
0
 protected void setHttpRequestHeader(HttpMethod method) {
   method.setRequestHeader(
       "Accept",
       "text/html,application/xhtml+xml,application/xml,application/json,image/jpeg,image/gif,*/*");
   method.setRequestHeader("Accept-Language", "zh-cn");
   method.setRequestHeader(
       "User-Agent",
       "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
   method.setRequestHeader("Accept-Charset", encoding);
   method.setRequestHeader("Keep-Alive", "300");
   method.setRequestHeader("Connection", "Keep-Alive");
   method.setRequestHeader("Cache-Control", "no-cache");
 }
 private HttpMethod createMethod(HttpMethodEnum httpMethodEnum, String url, HttpData httpData) {
   HttpMethod method = null;
   if (httpMethodEnum == HttpMethodEnum.GET) {
     method = this.createGetMethod(url);
   } else if (httpMethodEnum == HttpMethodEnum.POST) {
     method = this.createPostMethod(url, httpData);
   } else {
     method = this.createMultiPostMethod(url, httpData);
   }
   if (httpData != null) {
     if (httpData.getHttpHeader() != null) {
       method.setRequestHeader(
           httpData.getHttpHeader().getName(), httpData.getHttpHeader().getValue());
     }
   }
   return method;
 }
  private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT
        && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY
            || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

      Header location = method.getResponseHeader("Location");
      if (location == null) {
        location = method.getResponseHeader("location");
      }
      if (location != null) {
        Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());
        method.setURI(new URI(location.getValue(), true));
        Header destination = method.getRequestHeader("Destination");
        if (destination == null) {
          destination = method.getRequestHeader("destination");
        }
        if (destination != null) {
          String locationStr = location.getValue();
          int suffixIndex =
              locationStr.lastIndexOf(
                  (mCredentials instanceof OwnCloudBearerCredentials)
                      ? AccountUtils.ODAV_PATH
                      : AccountUtils.WEBDAV_PATH_4_0);
          String redirectionBase = locationStr.substring(0, suffixIndex);

          String destinationStr = destination.getValue();
          String destinationPath = destinationStr.substring(mBaseUri.toString().length());
          String redirectedDestination = redirectionBase + destinationPath;

          destination.setValue(redirectedDestination);
          method.setRequestHeader(destination);
        }
        status = super.executeMethod(method);
        redirectionsCount++;

      } else {
        Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
        status = HttpStatus.SC_NOT_FOUND;
      }
    }
    return status;
  }
Example #12
0
  /**
   * Gets the result of the execution of a get request. the attempt will be repeated several times
   * in case of failures
   *
   * @param path the path on which the request should be sent
   * @throws Exception if something's going wrong...
   */
  public void retryGetRequestUntilSucceed(@NonNull String path) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;

    log.debug("Sending GET request to " + fullpath + " with several attemps");

    final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY));
    final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY));

    final HttpMethod method = new GetMethod(fullpath);
    try {
      for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

      String responseAsString = null;
      int statusCode;
      int attempts = 0;
      boolean success = false;
      do {
        // waiting timeToWait seconds
        Thread.sleep(timeToWait * 1000);
        statusCode = httpClient.executeMethod(method);
        attempts++;
        // check for status code 200
        if (statusCode == HttpStatus.SC_OK) {
          responseAsString = method.getResponseBodyAsString();
          success = true;
          log.info("The result is available! ");
        } else
          log.warn(
              "unsuccessful GET request : "
                  + method.getStatusLine()
                  + " | Waiting "
                  + timeToWait
                  + " seconds ...");
      } while (!success && maxAttempts > attempts);
      response = new ResponseWrapper(responseAsString, statusCode);
    } catch (final Exception e) {
      log.error(e.getMessage(), e);
      throw e;
    } finally {
      method.releaseConnection();
    }
  }
Example #13
0
  /**
   * Allows to send a GET request to the path passed using the http client
   *
   * @param path the path on which the request should be sent
   */
  public void sendGetRequest(final String path) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;
    log.info("Sending GET request to " + fullpath);

    final HttpMethod method = new GetMethod(fullpath);
    try {
      for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());
      final int statusCode = httpClient.executeMethod(method);
      response =
          new ResponseWrapper(
              method.getResponseBodyAsString(), method.getResponseHeaders(), statusCode);
    } catch (final IOException e) {
      log.error(e.getMessage(), e);
      throw e;
    } finally {
      method.releaseConnection();
    }
  }
  private String post(final HttpMethod method) throws IOException, ForbiddenException {
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Accept-Encoding", "gzip");
    InputStream is = null;
    try {
      this.m_clientManager.executeMethod(method);
      final int statusCode = method.getStatusCode();
      final StatusLine statusLine = method.getStatusLine();
      final Header encoding = method.getResponseHeader("Content-Encoding");
      if (encoding != null && encoding.getValue().equals("gzip")) {
        m_log.debug("Unzipping body...");
        is = new GZIPInputStream(method.getResponseBodyAsStream());
      } else {
        is = method.getResponseBodyAsStream();
      }
      final String body = IOUtils.toString(is);
      if (StringUtils.isBlank(body)) {
        // Could easily be a post request, which would not have a body.
        m_log.debug("No response body.  Post request?");
      }
      if (statusCode == HttpStatus.SC_FORBIDDEN) {
        final String msg = "NO 200 OK: " + method.getURI() + "\n" + statusLine + "\n" + body;
        m_log.warn(msg);
        throw new ForbiddenException(msg);
      }

      if (statusCode != HttpStatus.SC_OK) {

        final String msg = "NO 200 OK: " + method.getURI() + "\n" + statusLine + "\n" + body;
        m_log.warn(msg);
        throw new IOException(msg);
      } else {
        m_log.debug("Got 200 response...");
      }

      return body;
    } finally {
      IOUtils.closeQuietly(is);
      method.releaseConnection();
    }
  }
  public JSONObject get(String path) throws Exception {
    JSONObject result;
    HttpMethod method = new GetMethod(repoHostname + ":" + repoHostPort + "/api/data/" + path);
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    method.setRequestHeader("Cookie", "jsonhub-store-key=" + getStoreKey());

    // client.getState().setCredentials(new AuthScope(null, repoHostPort, "authentication"), new
    // UsernamePasswordCredentials(memberId, memberPassword));

    // method.setDoAuthentication(true);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
      System.err.println("Method failed: " + method.getStatusLine());
      throw new GeneralException(method.getStatusLine().toString());
    } else {
      Reader reader = new InputStreamReader(method.getResponseBodyAsStream());
      CharArrayWriter cdata = new CharArrayWriter();
      char buf[] = new char[BUFFER_SIZE];
      int ret;
      while ((ret = reader.read(buf, 0, BUFFER_SIZE)) != -1) cdata.write(buf, 0, ret);

      reader.close();

      System.out.println("get response: " + cdata.toString());

      result = JSONObject.fromObject(cdata.toString());
    }

    method.releaseConnection();

    if (result.has("error")) throw new GeneralException(result.getString("error"));

    return result;
  }
 /**
  * Sets a header to notify server we expect a JSON-repsponse for this method.
  *
  * @param method
  */
 public static void setJSONExpected(HttpMethod method) {
   method.setRequestHeader(HEADER_ACCEPT, MIME_TYPE_JSON);
 }
 protected void applyRequestHeaders(HttpMethod method) {
   for (String name : requestHeaders.keySet()) {
     String value = requestHeaders.get(name);
     method.setRequestHeader(name, value);
   }
 }
  /**
   * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
   * form /userService/users. If CS throws an exception it handled and transalated to a Openfire
   * exception if possible. This is done using the check fault method that tries to throw the best
   * maching exception.
   *
   * @param type Must be GET or DELETE
   * @param urlSuffix The url suffix of the rest request
   * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
   * @return The response as a xml doc.
   * @throws ConnectionException Thrown if there are issues perfoming the request.
   * @throws Exception Thrown if the response from Clearspace contains an exception.
   */
  public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
      throws ConnectionException, Exception {
    if (Log.isDebugEnabled()) {
      Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
    }

    String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

    String secret = getSharedSecret();

    HttpClient client = new HttpClient();
    HttpMethod method;

    // Configures the authentication
    client.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
    AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
    client.getState().setCredentials(scope, credentials);

    // Creates the method
    switch (type) {
      case GET:
        method = new GetMethod(wsUrl);
        break;
      case POST:
        PostMethod pm = new PostMethod(wsUrl);
        StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
        pm.setRequestEntity(requestEntity);
        method = pm;
        break;
      case PUT:
        PutMethod pm1 = new PutMethod(wsUrl);
        StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
        pm1.setRequestEntity(requestEntity1);
        method = pm1;
        break;
      case DELETE:
        method = new DeleteMethod(wsUrl);
        break;
      default:
        throw new IllegalArgumentException();
    }

    method.setRequestHeader("Accept", "text/xml");
    method.setDoAuthentication(true);

    try {
      // Executes the request
      client.executeMethod(method);

      // Parses the result
      String body = method.getResponseBodyAsString();
      if (Log.isDebugEnabled()) {
        Log.debug("Outgoing REST call results: " + body);
      }

      // Checks the http status
      if (method.getStatusCode() != 200) {
        if (method.getStatusCode() == 401) {
          throw new ConnectionException(
              "Invalid password to connect to Clearspace.",
              ConnectionException.ErrorType.AUTHENTICATION);
        } else if (method.getStatusCode() == 404) {
          throw new ConnectionException(
              "Web service not found in Clearspace.", ConnectionException.ErrorType.PAGE_NOT_FOUND);
        } else if (method.getStatusCode() == 503) {
          throw new ConnectionException(
              "Web service not avaible in Clearspace.",
              ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE);
        } else {
          throw new ConnectionException(
              "Error connecting to Clearspace, http status code: " + method.getStatusCode(),
              new HTTPConnectionException(method.getStatusCode()),
              ConnectionException.ErrorType.OTHER);
        }
      } else if (body.contains("Clearspace Upgrade Console")) {
        // TODO Change CS to send a more standard error message
        throw new ConnectionException(
            "Clearspace is in an update state.", ConnectionException.ErrorType.UPDATE_STATE);
      }

      Element response = localParser.get().parseDocument(body).getRootElement();

      // Check for exceptions
      checkFault(response);

      // Since there is no exception, returns the response
      return response;
    } catch (DocumentException e) {
      throw new ConnectionException(
          "Error parsing the response of Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } catch (HttpException e) {
      throw new ConnectionException(
          "Error performing http request to Clearspace", e, ConnectionException.ErrorType.OTHER);
    } catch (UnknownHostException e) {
      throw new ConnectionException(
          "Unknown Host " + getConnectionURI() + " trying to connect to Clearspace",
          e,
          ConnectionException.ErrorType.UNKNOWN_HOST);
    } catch (IOException e) {
      throw new ConnectionException(
          "Error peforming http request to Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } finally {
      method.releaseConnection();
    }
  }
  public NamedList<Object> request(final SolrRequest request, ResponseParser processor)
      throws SolrServerException, IOException {
    HttpMethod method = null;
    InputStream is = null;
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
      path = "/select";
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
      parser = _parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original params
    ModifiableSolrParams wparams = new ModifiableSolrParams();
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (params == null) {
      params = wparams;
    } else {
      params = new DefaultSolrParams(wparams, params);
    }

    if (_invariantParams != null) {
      params = new DefaultSolrParams(_invariantParams, params);
    }

    int tries = _maxRetries + 1;
    try {
      while (tries-- > 0) {
        // Note: since we aren't do intermittent time keeping
        // ourselves, the potential non-timeout latency could be as
        // much as tries-times (plus scheduling effects) the given
        // timeAllowed.
        try {
          if (SolrRequest.METHOD.GET == request.getMethod()) {
            if (streams != null) {
              throw new SolrException(
                  SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
            }
            method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false));
          } else if (SolrRequest.METHOD.POST == request.getMethod()) {

            String url = _baseURL + path;
            boolean isMultipart = (streams != null && streams.size() > 1);

            if (streams == null || isMultipart) {
              PostMethod post = new PostMethod(url);
              post.getParams().setContentCharset("UTF-8");
              if (!this.useMultiPartPost && !isMultipart) {
                post.addRequestHeader(
                    "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
              }

              List<Part> parts = new LinkedList<Part>();
              Iterator<String> iter = params.getParameterNamesIterator();
              while (iter.hasNext()) {
                String p = iter.next();
                String[] vals = params.getParams(p);
                if (vals != null) {
                  for (String v : vals) {
                    if (this.useMultiPartPost || isMultipart) {
                      parts.add(new StringPart(p, v, "UTF-8"));
                    } else {
                      post.addParameter(p, v);
                    }
                  }
                }
              }

              if (isMultipart) {
                int i = 0;
                for (ContentStream content : streams) {
                  final ContentStream c = content;

                  String charSet = null;
                  String transferEncoding = null;
                  parts.add(
                      new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) {
                        @Override
                        protected long lengthOfData() throws IOException {
                          return c.getSize();
                        }

                        @Override
                        protected void sendData(OutputStream out) throws IOException {
                          InputStream in = c.getStream();
                          try {
                            IOUtils.copy(in, out);
                          } finally {
                            in.close();
                          }
                        }
                      });
                }
              }
              if (parts.size() > 0) {
                post.setRequestEntity(
                    new MultipartRequestEntity(
                        parts.toArray(new Part[parts.size()]), post.getParams()));
              }

              method = post;
            }
            // It is has one stream, it is the post body, put the params in the URL
            else {
              String pstr = ClientUtils.toQueryString(params, false);
              PostMethod post = new PostMethod(url + pstr);

              // Single stream as body
              // Using a loop just to get the first one
              final ContentStream[] contentStream = new ContentStream[1];
              for (ContentStream content : streams) {
                contentStream[0] = content;
                break;
              }
              if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                post.setRequestEntity(
                    new RequestEntity() {
                      public long getContentLength() {
                        return -1;
                      }

                      public String getContentType() {
                        return contentStream[0].getContentType();
                      }

                      public boolean isRepeatable() {
                        return false;
                      }

                      public void writeRequest(OutputStream outputStream) throws IOException {
                        ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);
                      }
                    });

              } else {
                is = contentStream[0].getStream();
                post.setRequestEntity(
                    new InputStreamRequestEntity(is, contentStream[0].getContentType()));
              }
              method = post;
            }
          } else {
            throw new SolrServerException("Unsupported method: " + request.getMethod());
          }
        } catch (NoHttpResponseException r) {
          // This is generally safe to retry on
          method.releaseConnection();
          method = null;
          if (is != null) {
            is.close();
          }
          // If out of tries then just rethrow (as normal error).
          if ((tries < 1)) {
            throw r;
          }
          // log.warn( "Caught: " + r + ". Retrying..." );
        }
      }
    } catch (IOException ex) {
      throw new SolrServerException("error reading streams", ex);
    }

    method.setFollowRedirects(_followRedirects);
    method.addRequestHeader("User-Agent", AGENT);
    if (_allowCompression) {
      method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));
    }

    try {
      // Execute the method.
      // System.out.println( "EXECUTE:"+method.getURI() );

      int statusCode = _httpClient.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        StringBuilder msg = new StringBuilder();
        msg.append(method.getStatusLine().getReasonPhrase());
        msg.append("\n\n");
        msg.append(method.getStatusText());
        msg.append("\n\n");
        msg.append("request: " + method.getURI());
        throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8"));
      }

      // Read the contents
      String charset = "UTF-8";
      if (method instanceof HttpMethodBase) {
        charset = ((HttpMethodBase) method).getResponseCharSet();
      }
      InputStream respBody = method.getResponseBodyAsStream();
      // Jakarta Commons HTTPClient doesn't handle any
      // compression natively.  Handle gzip or deflate
      // here if applicable.
      if (_allowCompression) {
        Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
        if (contentEncodingHeader != null) {
          String contentEncoding = contentEncodingHeader.getValue();
          if (contentEncoding.contains("gzip")) {
            // log.debug( "wrapping response in GZIPInputStream" );
            respBody = new GZIPInputStream(respBody);
          } else if (contentEncoding.contains("deflate")) {
            // log.debug( "wrapping response in InflaterInputStream" );
            respBody = new InflaterInputStream(respBody);
          }
        } else {
          Header contentTypeHeader = method.getResponseHeader("Content-Type");
          if (contentTypeHeader != null) {
            String contentType = contentTypeHeader.getValue();
            if (contentType != null) {
              if (contentType.startsWith("application/x-gzip-compressed")) {
                // log.debug( "wrapping response in GZIPInputStream" );
                respBody = new GZIPInputStream(respBody);
              } else if (contentType.startsWith("application/x-deflate")) {
                // log.debug( "wrapping response in InflaterInputStream" );
                respBody = new InflaterInputStream(respBody);
              }
            }
          }
        }
      }
      return processor.processResponse(respBody, charset);
    } catch (HttpException e) {
      throw new SolrServerException(e);
    } catch (IOException e) {
      throw new SolrServerException(e);
    } finally {
      method.releaseConnection();
      if (is != null) {
        is.close();
      }
    }
  }