Ejemplo n.º 1
0
 public static String encodeParameters(
     final List<HttpParameter> httpParams, final String splitter, final boolean quot) {
   final StringBuffer buf = new StringBuffer();
   for (final HttpParameter param : httpParams) {
     if (!param.isFile()) {
       if (buf.length() != 0) {
         if (quot) {
           buf.append("\"");
         }
         buf.append(splitter);
       }
       buf.append(HttpParameter.encode(param.getName())).append("=");
       if (quot) {
         buf.append("\"");
       }
       buf.append(HttpParameter.encode(param.getValue()));
     }
   }
   if (buf.length() != 0) {
     if (quot) {
       buf.append("\"");
     }
   }
   return buf.toString();
 }
Ejemplo n.º 2
0
  @Override
  public HttpResponse request(final HttpRequest req) throws MoefouException {
    int retriedCount;
    final int retry = CONF.getHttpRetryCount() + 1;
    HttpResponse res = null;
    for (retriedCount = 0; retriedCount < retry; retriedCount++) {
      int responseCode = -1;
      try {
        HttpURLConnection con;
        OutputStream os = null;
        try {
          con = getConnection(req.getURL());
          con.setDoInput(true);
          setHeaders(req, con);
          con.setRequestMethod(req.getMethod().name());
          if (req.getMethod() == POST) {
            if (HttpParameter.containsFile(req.getParameters())) {
              String boundary = "----Twitter4J-upload" + System.currentTimeMillis();
              con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
              boundary = "--" + boundary;
              con.setDoOutput(true);
              os = con.getOutputStream();
              final DataOutputStream out = new DataOutputStream(os);
              for (final HttpParameter param : req.getParameters()) {
                if (param.isFile()) {
                  write(out, boundary + "\r\n");
                  write(
                      out,
                      "Content-Disposition: form-data; name=\""
                          + param.getName()
                          + "\"; filename=\""
                          + param.getFile().getName()
                          + "\"\r\n");
                  write(out, "Content-Type: " + param.getContentType() + "\r\n\r\n");
                  final BufferedInputStream in =
                      new BufferedInputStream(
                          param.hasFileBody()
                              ? param.getFileBody()
                              : new FileInputStream(param.getFile()));
                  int buff;
                  while ((buff = in.read()) != -1) {
                    out.write(buff);
                  }
                  write(out, "\r\n");
                  in.close();
                } else {
                  write(out, boundary + "\r\n");
                  write(
                      out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"\r\n");
                  write(out, "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
                  logger.debug(param.getValue());
                  out.write(param.getValue().getBytes("UTF-8"));
                  write(out, "\r\n");
                }
              }
              write(out, boundary + "--\r\n");
              write(out, "\r\n");

            } else {
              con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
              final String postParam = HttpParameter.encodeParameters(req.getParameters());
              logger.debug("Post Params: ", postParam);
              final byte[] bytes = postParam.getBytes("UTF-8");
              con.setRequestProperty("Content-Length", Integer.toString(bytes.length));
              con.setDoOutput(true);
              os = con.getOutputStream();
              os.write(bytes);
            }
            os.flush();
            os.close();
          }
          res = new HttpResponseImpl(con, CONF);
          responseCode = con.getResponseCode();
          if (logger.isDebugEnabled()) {
            logger.debug("Response: ");
            final Map<String, List<String>> responseHeaders = con.getHeaderFields();
            for (final String key : responseHeaders.keySet()) {
              final List<String> values = responseHeaders.get(key);
              for (final String value : values) {
                if (key != null) {
                  logger.debug(key + ": " + value);
                } else {
                  logger.debug(value);
                }
              }
            }
          }
          if (responseCode < OK || responseCode != FOUND && MULTIPLE_CHOICES <= responseCode) {
            if (responseCode == ENHANCE_YOUR_CLAIM
                || responseCode == BAD_REQUEST
                || responseCode < INTERNAL_SERVER_ERROR
                || retriedCount == CONF.getHttpRetryCount())
              throw new MoefouException(res.asString(), req, res);
          } else {
            break;
          }
        } finally {
          try {
            os.close();
          } catch (final Exception ignore) {
          }
        }
      } catch (final IOException ioe) {
        // connection timeout or read timeout
        if (retriedCount == CONF.getHttpRetryCount())
          // throw new TwitterException(ioe.getMessage(), ioe,
          // responseCode);
          throw new MoefouException(ioe.getMessage(), req, res);
      } catch (final NullPointerException e) {
        // This exception will be thown when URL is invalid.
        throw new MoefouException("The URL requested is invalid.", e);
      } catch (final OutOfMemoryError e) {
        throw new MoefouException(e.getMessage(), e);
      }
      try {
        if (logger.isDebugEnabled() && res != null) {
          res.asString();
        }
        logger.debug(
            "Sleeping " + CONF.getHttpRetryIntervalSeconds() + " seconds until the next retry.");
        Thread.sleep(CONF.getHttpRetryIntervalSeconds() * 1000);
      } catch (final InterruptedException ignore) {
        // nothing to do
      }
    }
    return res;
  }