Ejemplo n.º 1
0
 private boolean fetchApp(String url, String username, String password) throws JSONException {
   try {
     if (username == "null") {
       username = null;
     }
     if (password == "null") {
       password = null;
     }
     HttpResponse response = makeRequest(url, username, password);
     StatusLine sl = response.getStatusLine();
     int code = sl.getStatusCode();
     HttpEntity entity = response.getEntity();
     InputStream content = entity.getContent();
     if (code != 200) {
       return false;
     } else {
       ZipInputStream data = new ZipInputStream(content);
       return saveAndVerify(data);
     }
   } catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     return false;
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     return false;
   }
 }
Ejemplo n.º 2
0
    /**
     * Parse the room read response received from reservation backend.
     *
     * <p>This will request the retry if the response status code differs from 200, 201 or 4xx.
     *
     * @param response The Apache HTTP client response
     * @throws IOException
     * @throws ParseException
     * @throws FaultTolerantRESTRequest.RetryRequestedException
     */
    @Override
    protected void parse(HttpResponse response)
        throws IOException, ParseException, FaultTolerantRESTRequest.RetryRequestedException {

      int statusCode = response.getStatusLine().getStatusCode();

      logger.info("STATUS CODE: " + statusCode);

      if (200 == statusCode || 201 == statusCode) {
        // OK
        conference = readConferenceResponse(conference, response);

        result = new ApiResult(statusCode, conference);
      } else if ((statusCode >= 400) && (statusCode < 500)) {
        // Client side error, indicates that the reservation
        // backend do not want the resubmission
        ErrorResponse error = readErrorResponse(response);

        result = new ApiResult(statusCode, error);

      } else {

        // Unusual status code, request the retry
        throw new FaultTolerantRESTRequest.RetryRequestedException();
      }
    }
Ejemplo n.º 3
0
  private String dealWithError(HttpResponse httpResponse) throws WeiboException {

    StatusLine status = httpResponse.getStatusLine();
    int statusCode = status.getStatusCode();

    String result = "";

    if (statusCode != HttpStatus.SC_OK) {

      result = readResult(httpResponse);
      String err = null;
      int errCode = 0;
      try {
        JSONObject json = new JSONObject(result);
        err = json.getString("error");
        errCode = json.getInt("error_code");
        WeiboException exception = new WeiboException();
        exception.setError_code(errCode);
        exception.setOriError(err);
        throw exception;

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

    return result;
  }
Ejemplo n.º 4
0
 private String sendBasic(HttpRequestBase request) throws HttpException {
   try {
     HttpResponse response = httpClient.execute(request);
     HttpEntity entity = response.getEntity();
     String body = "";
     if (entity != null) {
       body = EntityUtils.toString(entity, UTF_8);
       if (entity.getContentType() == null) {
         body = new String(body.getBytes(ISO_8859_1), UTF_8);
       }
     }
     int code = response.getStatusLine().getStatusCode();
     if (code < 200 || code >= 300) {
       throw new Exception(String.format(" code : '%s' , body : '%s'", code, body));
     }
     return body;
   } catch (Exception ex) {
     throw new HttpException(
         "Fail to send "
             + request.getMethod()
             + " request to url "
             + request.getURI()
             + ", "
             + ex.getMessage(),
         ex);
   } finally {
     request.releaseConnection();
   }
 }
Ejemplo n.º 5
0
  public String readResponse(HttpResponse response) {
    String output = "";

    HttpEntity entity = response.getEntity();

    try {
      trapException(response.getStatusLine().getStatusCode());
    } catch (CrowdFlowerException e1) {
      e1.printStackTrace();
    }

    InputStream instream;
    try {
      instream = entity.getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(instream));

      // do something useful with the response
      output = output + reader.readLine();
      instream.close();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return output;
  }
Ejemplo n.º 6
0
 public void run() {
   HttpPost httpPost =
       new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
   //
   httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
   //
   HttpResponse response = null; // This is acting as keep alive.
   //
   while (isActive()) {
     try {
       Thread.sleep(KEEP_ALIVE_PERIOD);
       httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
       response = null;
       response = httpclient.execute(httpPost);
       int status = response.getStatusLine().getStatusCode();
       if (status != RestStreamHanlder.SUCCESS_200) {
         logger.error(
             "Cant register to the remote client, retrying in:"
                 + (KEEP_ALIVE_PERIOD / 1000)
                 + " seconds.");
         structure = registerAndGetStructure();
       }
     } catch (Exception e) {
       logger.warn(e.getMessage(), e);
     } finally {
       if (response != null) {
         try {
           response.getEntity().getContent().close();
         } catch (Exception e) {
           logger.warn(e.getMessage(), e);
         }
       }
     }
   }
 }
Ejemplo n.º 7
0
 public String readTwitterFeed() {
   StringBuilder builder = new StringBuilder();
   HttpClient client = new DefaultHttpClient();
   HttpGet httpGet = new HttpGet("http:'//twitter.com/users/show/vogella.json");
   try {
     HttpResponse response = client.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     int statusCode = statusLine.getStatusCode();
     if (statusCode == 200) {
       HttpEntity entity = response.getEntity();
       InputStream content = entity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(content));
       String line;
       while ((line = reader.readline()) != null) {
         builder.append(line);
       }
     } else {
       Log.e(MainActivity2.class.toString(), "Failed to download file");
     }
   } catch (ClientProtocolExpcetion e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return builder.toString();
 }
Ejemplo n.º 8
0
 public static void logResponse(Logger logger, HttpResponse response, String prefix) {
   if (logger.isDebugEnabled()) {
     logger.debug("%s %s", prefix, response.getStatusLine().toString());
     for (Entry<String, String> header : response.getHeaders().entries()) {
       logger.debug("%s %s: %s", prefix, header.getKey(), header.getValue());
     }
   }
 }
Ejemplo n.º 9
0
 public HttpResponseException(HttpCommand command, HttpResponse response, String content) {
   this(
       String.format(
           "command: %s failed with response: %s; content: [%s]",
           command.getCurrentRequest().getRequestLine(), response.getStatusLine(), content),
       command,
       response,
       content);
 }
Ejemplo n.º 10
0
 public HttpResponseException(HttpCommand command, HttpResponse response, Throwable cause) {
   this(
       String.format(
           "command: %1$s failed with response: %2$s",
           command.getCurrentRequest().getRequestLine(), response.getStatusLine()),
       command,
       response,
       cause);
 }
Ejemplo n.º 11
0
  private String dealWithResponse(HttpResponse httpResponse) throws WeiboException {

    StatusLine status = httpResponse.getStatusLine();
    int statusCode = status.getStatusCode();

    if (statusCode != HttpStatus.SC_OK) {
      return dealWithError(httpResponse);
    }

    return readResult(httpResponse);
  }
Ejemplo n.º 12
0
 public HttpResponseException(HttpCommand command, HttpResponse response) {
   this(
       String.format(
           "request: %s %sfailed with response: %s",
           command.getCurrentRequest().getRequestLine(),
           requestPayloadIfStringOrFormIfNotReturnEmptyString(
               (HttpRequest) command.getCurrentRequest()),
           response.getStatusLine()),
       command,
       response);
 }
 public Result<InputStream> getInputStream(String endpoint) throws IOException {
   HttpClient cli = createClient();
   HttpGet get = createGet(endpoint);
   HttpResponse res = cli.execute(get);
   Object result = null;
   if (res.getStatusLine().getStatusCode() == 200) result = res.getEntity().getContent();
   else {
     RestResponse resp = new RestResponse(res);
     result = unmarshalPOJO(resp, InputStream.class);
     cli.getConnectionManager().shutdown();
   }
   return new Result<InputStream>(result);
 }
Ejemplo n.º 14
0
  YammerHttpResponse execute(ApiQuery query) {
    HttpUriRequest request = generateRequest(query);
    setHeader(request);

    try {
      HttpResponse httpResponse = this.httpClient.execute(request);
      return new YammerHttpResponse(
          httpResponse.getStatusLine().getStatusCode(),
          readEntityAsString(httpResponse.getEntity()));
    } catch (IOException e) {
      return new YammerHttpResponse(e);
    }
  }
Ejemplo n.º 15
0
    protected String resolveURL(ApiWrapper wrapper, String url) throws IOException {
      String result = "";

      HttpResponse reso = wrapper.head(Request.to(Endpoints.RESOLVE).with("url", url));
      if (reso.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY)
        throw new CloudAPI.ResolverException("Invalid status code", reso);

      // Header location = reso.getFirstHeader("Location");
      if (!reso.containsHeader("Location"))
        throw new CloudAPI.ResolverException("No location header", reso);
      result = reso.getFirstHeader("Location").getValue();

      return result;
    }
Ejemplo n.º 16
0
 /**
  * Validates a HTTP response; on error cases logs status and throws relevant exceptions.
  *
  * @param response The HTTP response.
  */
 private void validate(HttpResponse response) throws IOException {
   int code = response.getStatusLine().getStatusCode();
   if (code == 200 || code == 201 || code == 202) { // success (ok | created | accepted)
     return;
   }
   String msg = format("<< Status: %s (%s) ", code, response.getStatusLine().getReasonPhrase());
   switch (code) {
     case HttpStatus.SC_NOT_FOUND:
       {
         log.info(msg);
         throw new NoDocumentException(msg);
       }
     case HttpStatus.SC_CONFLICT:
       {
         log.warn(msg);
         throw new DocumentConflictException(msg);
       }
     default:
       { // other errors: 400 | 401 | 500 etc.
         log.error(msg += EntityUtils.toString(response.getEntity()));
         throw new CouchDbException(msg);
       }
   }
 }
Ejemplo n.º 17
0
 /**
  * Performs request method with HttpContext. HttpContext typically contains cookie store with all
  * cookies to include with request
  *
  * @param method request method
  * @param context httpcontext
  * @return request response
  * @throws Exception
  */
 protected HttpResponse perform(HttpRequestBase method, HttpContext context) throws Exception {
   HttpResponse response = getHttpClient().execute(method, context);
   Header cspHeaders[] = response.getHeaders(CSP.Header.REPORT_ONLY);
   if (response.getStatusLine().getStatusCode() == 200) {
     // TODO(fabbott): Although a request for e.g. moment.js from testSetRunner.app
     // does have a header, the same request from AuraFrameworkServletHttpTest does
     // not.  I suspect this is because the test has no UID, but the "real life" one
     // does... but for now, let's validate the CSP header only if it's actually there.
     if (cspHeaders.length != 0) {
       assertEquals(1, cspHeaders.length);
       assertTrue(
           "No connect-src in default CSP",
           cspHeaders[0].getValue().contains("; connect-src 'self';"));
     }
   }
   return response;
 }
Ejemplo n.º 18
0
 /**
  * Returns the lock token, which must be retained to unlock the resource
  *
  * @param uri - must be encoded
  * @param owner
  * @return
  * @throws com.ettrema.httpclient.HttpException
  */
 public synchronized String doLock(String uri)
     throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException,
         BadRequestException, NotFoundException, URISyntaxException {
   notifyStartRequest();
   LockMethod p = new LockMethod(uri);
   try {
     String lockXml = LOCK_XML.replace("${owner}", user);
     HttpEntity requestEntity = new StringEntity(lockXml, "UTF-8");
     p.setEntity(requestEntity);
     HttpResponse resp = host().client.execute(p);
     int result = resp.getStatusLine().getStatusCode();
     Utils.processResultCode(result, uri);
     return p.getLockToken(resp);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Ejemplo n.º 19
0
 /**
  * @param newUri - must be fully qualified and correctly encoded
  * @return
  * @throws com.ettrema.httpclient.HttpException
  */
 public synchronized int doMkCol(String newUri)
     throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException,
         BadRequestException, NotFoundException, URISyntaxException {
   notifyStartRequest();
   MkColMethod p = new MkColMethod(newUri);
   try {
     HttpResponse resp = host().client.execute(p);
     int result = resp.getStatusLine().getStatusCode();
     if (result == 409) {
       // probably means the folder already exists
       return result;
     }
     Utils.processResultCode(result, newUri);
     return result;
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Ejemplo n.º 20
0
  public Either<IOException, HttpResponse> execRequest(HttpUriRequest httpReq, String acceptType) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpReq.setHeader("accept", acceptType);
    for (Header header : getHeaders()) {
      httpReq.setHeader(header);
    }

    try {
      HttpResponse resp = httpClient.execute(httpReq);
      Log.i(
          TAG,
          String.format(
              "%s %s %s => %d",
              httpReq.getRequestLine().getMethod(),
              httpReq.getRequestLine().getUri(),
              httpReq.getParams(),
              resp.getStatusLine().getStatusCode()));
      return new Right<IOException, HttpResponse>(resp);
    } catch (IOException e) {
      return new Left<IOException, HttpResponse>(e);
    }
  }
Ejemplo n.º 21
0
  public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull URI uri)
      throws CloudException, InternalException {
    logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")");
    wire.debug("--------------------------------------------------------> " + uri.toASCIIString());

    try {
      HttpClient client = getClient();
      HttpUriRequest get = new HttpGet(uri);

      if (uri.toString().indexOf("/services/images") > -1) {
        get.addHeader("x-ms-version", "2012-08-01");
      } else if (uri.toString().contains("/services/vmimages")) {
        get.addHeader("x-ms-version", "2014-05-01");
      } else {
        get.addHeader("x-ms-version", "2012-03-01");
      }

      if (strategy != null && strategy.getSendAsHeader()) {
        get.addHeader(strategy.getHeaderName(), strategy.getRequestId());
      }

      wire.debug(get.getRequestLine().toString());
      for (Header header : get.getAllHeaders()) {
        wire.debug(header.getName() + ": " + header.getValue());
      }

      HttpResponse response;
      StatusLine status;

      try {
        response = client.execute(get);
        status = response.getStatusLine();
      } catch (IOException e) {
        logger.error(
            "get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
        throw new CloudException(e);
      }

      logger.debug("get(): HTTP Status " + status);

      Header[] headers = response.getAllHeaders();

      wire.debug(status.toString());
      for (Header h : headers) {
        if (h.getValue() != null) {
          wire.debug(h.getName() + ": " + h.getValue().trim());
        } else {
          wire.debug(h.getName() + ":");
        }
      }

      if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {
        return null;
      }
      if (status.getStatusCode() != HttpServletResponse.SC_OK
          && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
        logger.error("get(): Expected OK for GET request, got " + status.getStatusCode());

        HttpEntity entity = response.getEntity();
        String body;

        if (entity == null) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              "An error was returned without explanation");
        }
        try {
          body = EntityUtils.toString(entity);
        } catch (IOException e) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              e.getMessage());
        }

        wire.debug(body);

        AzureException.ExceptionItems items =
            AzureException.parseException(status.getStatusCode(), body);

        if (items == null) {
          return null;
        }
        logger.error(
            "get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
        throw new AzureException(items);
      } else {
        HttpEntity entity = response.getEntity();

        if (entity == null) {
          return null;
        }
        InputStream input;

        try {
          input = entity.getContent();
        } catch (IOException e) {
          logger.error(
              "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
          throw new CloudException(e);
        }

        wire.debug("---> Binary Data <---");
        return input;
      }
    } finally {
      logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
      wire.debug(
          "--------------------------------------------------------> " + uri.toASCIIString());
    }
  }
Ejemplo n.º 22
0
  public DataField[] registerAndGetStructure() throws IOException, ClassNotFoundException {
    // Create the POST request
    HttpPost httpPost =
        new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
    // Add the POST parameters
    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
    //
    httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
    // Create local execution context
    HttpContext localContext = new BasicHttpContext();
    //
    NotificationRegistry.getInstance().addNotification(uid, this);
    int tries = 0;
    AuthState authState = null;
    //
    while (tries < 2) {
      tries++;
      HttpResponse response = null;
      try {
        // Execute the POST request
        response = httpclient.execute(httpPost, localContext);
        //
        int sc = response.getStatusLine().getStatusCode();
        //
        if (sc == HttpStatus.SC_OK) {
          logger.debug(
              new StringBuilder()
                  .append("Wants to consume the structure packet from ")
                  .append(initParams.getRemoteContactPoint())
                  .toString());
          structure = (DataField[]) XSTREAM.fromXML(response.getEntity().getContent());
          logger.debug("Connection established for: " + initParams.getRemoteContactPoint());
          break;
        } else {
          if (sc == HttpStatus.SC_UNAUTHORIZED)
            authState =
                (AuthState)
                    localContext.getAttribute(
                        ClientContext.TARGET_AUTH_STATE); // Target host authentication required
          else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            authState =
                (AuthState)
                    localContext.getAttribute(
                        ClientContext.PROXY_AUTH_STATE); // Proxy authentication required
          else {
            logger.error(
                new StringBuilder()
                    .append("Unexpected POST status code returned: ")
                    .append(sc)
                    .append("\nreason: ")
                    .append(response.getStatusLine().getReasonPhrase())
                    .toString());
          }
          if (authState != null) {
            if (initParams.getUsername() == null
                || (tries > 1 && initParams.getUsername() != null)) {
              logger.error(
                  "A valid username/password required to connect to the remote host: "
                      + initParams.getRemoteContactPoint());
            } else {

              AuthScope authScope = authState.getAuthScope();
              logger.warn(
                  new StringBuilder()
                      .append("Setting Credentials for host: ")
                      .append(authScope.getHost())
                      .append(":")
                      .append(authScope.getPort())
                      .toString());
              Credentials creds =
                  new UsernamePasswordCredentials(
                      initParams.getUsername(), initParams.getPassword());
              httpclient.getCredentialsProvider().setCredentials(authScope, creds);
            }
          }
        }
      } catch (RuntimeException ex) {
        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        logger.warn("Aborting the HTTP POST request.");
        httpPost.abort();
        throw ex;
      } finally {
        if (response != null && response.getEntity() != null) {
          response.getEntity().consumeContent();
        }
      }
    }

    if (structure == null) throw new RuntimeException("Cannot connect to the remote host.");

    return structure;
  }
Ejemplo n.º 23
0
 /**
  * Gets status code of response
  *
  * @param response request response
  * @return status code
  */
 protected static int getStatusCode(HttpResponse response) {
   return response.getStatusLine().getStatusCode();
 }
Ejemplo n.º 24
0
  public void tempRedirectInvoke(
      @Nonnull String tempEndpoint,
      @Nonnull String method,
      @Nonnull String account,
      @Nonnull String resource,
      @Nonnull String body)
      throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
      logger.trace(
          "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }
    if (wire.isDebugEnabled()) {
      wire.debug(
          "POST --------------------------------------------------------> "
              + endpoint
              + account
              + resource);
      wire.debug("");
    }
    try {
      HttpClient client = getClient();
      String url = tempEndpoint + account + resource;

      HttpRequestBase httpMethod = getMethod(method, url);

      // If it is networking configuration services
      if (httpMethod instanceof HttpPut) {
        if (url.endsWith("/services/networking/media")) {
          httpMethod.addHeader("Content-Type", "text/plain");
        } else {
          httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
        }
      } else {
        httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
      }

      // dmayne version is older for anything to do with images and for disk deletion
      if (url.indexOf("/services/images") > -1
          || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
        httpMethod.addHeader("x-ms-version", "2012-08-01");
      } else {
        httpMethod.addHeader("x-ms-version", "2012-03-01");
      }

      if (strategy != null && strategy.getSendAsHeader()) {
        httpMethod.addHeader(strategy.getHeaderName(), strategy.getRequestId());
      }

      if (wire.isDebugEnabled()) {
        wire.debug(httpMethod.getRequestLine().toString());
        for (Header header : httpMethod.getAllHeaders()) {
          wire.debug(header.getName() + ": " + header.getValue());
        }
        wire.debug("");
        if (body != null) {
          wire.debug(body);
          wire.debug("");
        }
      }

      if (httpMethod instanceof HttpEntityEnclosingRequestBase) {

        HttpEntityEnclosingRequestBase entityEnclosingMethod =
            (HttpEntityEnclosingRequestBase) httpMethod;

        if (body != null) {
          try {
            entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8"));
          } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }

      HttpResponse response;
      StatusLine status;

      try {
        response = client.execute(httpMethod);
        status = response.getStatusLine();
      } catch (IOException e) {
        logger.error(
            "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
        if (logger.isTraceEnabled()) {
          e.printStackTrace();
        }
        throw new CloudException(e);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("post(): HTTP Status " + status);
      }
      Header[] headers = response.getAllHeaders();

      if (wire.isDebugEnabled()) {
        wire.debug(status.toString());
        for (Header h : headers) {
          if (h.getValue() != null) {
            wire.debug(h.getName() + ": " + h.getValue().trim());
          } else {
            wire.debug(h.getName() + ":");
          }
        }
        wire.debug("");
      }
      if (status.getStatusCode() != HttpServletResponse.SC_OK
          && status.getStatusCode() != HttpServletResponse.SC_CREATED
          && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
        logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

        HttpEntity entity = response.getEntity();

        if (entity == null) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              "An error was returned without explanation");
        }
        try {
          body = EntityUtils.toString(entity);
        } catch (IOException e) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              e.getMessage());
        }
        if (wire.isDebugEnabled()) {
          wire.debug(body);
        }
        wire.debug("");
        AzureException.ExceptionItems items =
            AzureException.parseException(status.getStatusCode(), body);

        if (items == null) {
          throw new CloudException(
              CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
        }
        logger.error(
            "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
        throw new AzureException(items);
      }
    } finally {
      if (logger.isTraceEnabled()) {
        logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
      }
      if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(
            "POST --------------------------------------------------------> "
                + endpoint
                + account
                + resource);
      }
    }
  }
  /** 连接网络读取数据 */
  @Override
  protected <T> void connectWithRetries(AbstractRequest<T> request, InternalResponse response)
      throws HttpClientException, HttpNetException, HttpServerException {

    // if(true) {
    //    throw new HttpNetException(NetException.NetworkDisabled);
    // }

    // 1. create apache request
    final HttpUriRequest apacheRequest = createApacheRequest(request);

    // 2. update http header
    if (request.getHeaders() != null) {
      Set<Entry<String, String>> set = request.getHeaders().entrySet();
      for (Entry<String, String> en : set) {
        apacheRequest.setHeader(new BasicHeader(en.getKey(), en.getValue()));
      }
    }

    // 3. try to connect
    HttpListener<T> listener = request.getHttpListener();
    StatisticsListener statistic = response.getStatistics();
    int times = 0,
        maxRetryTimes = request.getMaxRetryTimes(),
        maxRedirectTimes = request.getMaxRedirectTimes();
    boolean retry = true;
    IOException cause = null;
    while (retry) {
      try {
        cause = null;
        retry = false;
        if (request.isCancelledOrInterrupted()) {
          return;
        }
        if (statistic != null) {
          statistic.onPreConnect(request);
        }
        HttpResponse ares = mHttpClient.execute(apacheRequest);
        if (statistic != null) {
          statistic.onAfterConnect(request);
        }
        // status
        StatusLine status = ares.getStatusLine();
        HttpStatus httpStatus = new HttpStatus(status.getStatusCode(), status.getReasonPhrase());
        response.setHttpStatus(httpStatus);
        // header
        Header[] headers = ares.getAllHeaders();
        if (headers != null) {
          com.litesuits.http.data.NameValuePair hs[] =
              new com.litesuits.http.data.NameValuePair[headers.length];
          for (int i = 0; i < headers.length; i++) {
            String name = headers[i].getName();
            String value = headers[i].getValue();
            if ("Content-Length".equalsIgnoreCase(name)) {
              response.setContentLength(Long.parseLong(value));
            }
            hs[i] = new com.litesuits.http.data.NameValuePair(name, value);
          }
          response.setHeaders(hs);
        }

        // data body
        if (status.getStatusCode() <= 299 || status.getStatusCode() == 600) {
          // 成功
          HttpEntity entity = ares.getEntity();
          if (entity != null) {
            // charset
            String charSet = getCharsetFromEntity(entity, request.getCharSet());
            response.setCharSet(charSet);
            // is cancelled ?
            if (request.isCancelledOrInterrupted()) {
              return;
            }
            // length
            long len = response.getContentLength();
            DataParser<T> parser = request.getDataParser();
            if (statistic != null) {
              statistic.onPreRead(request);
            }
            parser.readFromNetStream(entity.getContent(), len, charSet);
            if (statistic != null) {
              statistic.onAfterRead(request);
            }
            response.setReadedLength(parser.getReadedLength());
            endEntityViaReflection(entity);
          }
          return;
        } else if (status.getStatusCode() <= 399) {
          // redirect
          if (response.getRedirectTimes() < maxRedirectTimes) {
            // get the location header to find out where to redirect to
            Header locationHeader = ares.getFirstHeader(Consts.REDIRECT_LOCATION);
            if (locationHeader != null) {
              String location = locationHeader.getValue();
              if (location != null && location.length() > 0) {
                if (!location.toLowerCase().startsWith("http")) {
                  URI uri = new URI(request.getFullUri());
                  URI redirect = new URI(uri.getScheme(), uri.getHost(), location, null);
                  location = redirect.toString();
                }
                response.setRedirectTimes(response.getRedirectTimes() + 1);
                request.setUri(location);
                if (HttpLog.isPrint) {
                  HttpLog.i(TAG, "Redirect to : " + location);
                }
                if (listener != null) {
                  listener.notifyCallRedirect(
                      request, maxRedirectTimes, response.getRedirectTimes());
                }
                connectWithRetries(request, response);
                return;
              }
            }
            throw new HttpServerException(httpStatus);
          } else {
            throw new HttpServerException(ServerException.RedirectTooMuch);
          }
        } else if (status.getStatusCode() <= 499) {
          // 客户端被拒
          throw new HttpServerException(httpStatus);
        } else if (status.getStatusCode() < 599) {
          // 服务器有误
          throw new HttpServerException(httpStatus);
        }
      } catch (IOException e) {
        cause = e;
      } catch (NullPointerException e) {
        // bug in HttpClient 4.0.x, see http://code.google.com/p/android/issues/detail?id=5255
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
          cause = new IOException(e.getMessage());
        } else {
          cause = new IOException(e);
        }
      } catch (URISyntaxException e) {
        throw new HttpClientException(e);
      } catch (IllegalStateException e) {
        // for apache http client. if url is illegal, it usually raises an exception as
        // "IllegalStateException:
        // Scheme 'xxx' not registered."
        throw new HttpClientException(e);
      } catch (SecurityException e) {
        throw new HttpClientException(e, ClientException.PermissionDenied);
      } catch (RuntimeException e) {
        throw new HttpClientException(e);
      }
      if (cause != null) {
        try {
          if (request.isCancelledOrInterrupted()) {
            return;
          }
          times++;
          retry =
              retryHandler.retryRequest(
                  cause, times, maxRetryTimes, mHttpContext, config.getContext());
        } catch (InterruptedException e) {
          e.printStackTrace();
          return;
        }
        if (retry) {
          response.setRetryTimes(times);
          if (HttpLog.isPrint) {
            HttpLog.i(TAG, "LiteHttp retry request: " + request.getUri());
          }
          if (listener != null) {
            listener.notifyCallRetry(request, maxRetryTimes, times);
          }
        }
      }
    }
    if (cause != null) {
      throw new HttpNetException(cause);
    }
  }
Ejemplo n.º 26
0
    @Override
    protected String doInBackground(Void... voidstr) {
      JSONObject jsonObject = new JSONObject();

      try {
        jsonObject.accumulate("firstName", firstName);
        jsonObject.accumulate("lastName", lastName);
        jsonObject.accumulate("phoneNumber", phoneNumber);
        jsonObject.accumulate("address", addr);

        // Add a nested JSONObject (e.g. for header information)
        JSONObject header = new JSONObject();
        header.put("deviceType", "Android"); // Device type
        header.put("deviceVersion", "2.0"); // Device OS version
        header.put("language", "es-es"); // Language of the Android client
        jsonObject.put("header", header);
        // Output the JSON object we're sending to Logcat:

        URL = "http://162.243.114.166/cgi-bin/Database_scripts/Registration_script.py";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);
        System.out.println("printing json object : " + jsonObject);
        String se;
        se = jsonObject.toString();
        System.out.println("printing se : " + se);

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        System.out.println("printing req : " + httpPostRequest.getEntity().getContent().toString());
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        // httpPostRequest.setHeader("Content-length", IntegejsonObjSend.toString().length());
        // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you
        // would like to use gzip compression

        InputStream inp = httpPostRequest.getEntity().getContent();
        String req = convertStreamToString(inp);
        System.out.println("printing entities : " + req);

        System.out.println("printing http request message : message is :" + httpPostRequest);
        HttpResponse response = null;
        try {
          response = (HttpResponse) httpclient.execute(httpPostRequest);
        } catch (Exception ex) {
          System.out.println("printing error :" + ex);
        }
        InputStream is = response.getEntity().getContent();
        String res = convertStreamToString(is);
        System.out.println("printing Response is :" + res);
        System.out.println("printing response code : " + response.getStatusLine().getStatusCode());

        // Get hold of the response entity (-> the data)
        HttpEntity entity = response.getEntity();
        String serverresp = entity.toString();
        System.out.println(
            "printing server response, entity length : " + entity.getContentLength());
        System.out.println("printing server response : " + serverresp);

        if (entity != null) {
          // Read the content stream
          InputStream instream = entity.getContent();
          Header contentEncoding = response.getFirstHeader("Content-Encoding");
          if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
          }
          System.out.println("Debug point : 1.3");
          // convert content stream to a String
          String resultString = convertStreamToString(instream);
          instream.close();
          resultString =
              resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

          // Transform the String into a JSONObject
          JSONObject jsonObjRecv = new JSONObject(resultString);
          // Raw DEBUG output of our received JSON object:
          Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");
          System.out.println("Debug point : 1.4");
          return jsonObjRecv;
        }
        // return serverresp;

        try {
          // Add your data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
          nameValuePairs.add(new BasicNameValuePair("q", se));
          httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          System.out.println("printing http params: " + httpPostRequest.getParams().toString());
          // Execute HTTP Post Request
          HttpResponse response = httpclient.execute(httpPostRequest);

        } catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
        } catch (IOException e) {
          // TODO Auto-generated catch block
        }
      } catch (Exception e) {
        System.out.println("Debug point : 1.4(a)");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
      }
      return null;
    }
Ejemplo n.º 27
0
 public void logResponse(Logger logger, HttpResponse response, String prefix) {
   if (logger.isDebugEnabled()) {
     logger.debug("%s %s", prefix, response.getStatusLine().toString());
     logMessage(logger, response, prefix);
   }
 }
Ejemplo n.º 28
0
  public String post(@Nonnull String account, @Nonnull String resource, @Nonnull String body)
      throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
      logger.trace(
          "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }
    if (wire.isDebugEnabled()) {
      wire.debug(
          "POST --------------------------------------------------------> "
              + endpoint
              + account
              + resource);
      wire.debug("");
    }
    String requestId = null;
    try {
      HttpClient client = getClient();
      String url = endpoint + account + resource;

      HttpPost post = new HttpPost(url);

      if (url.toLowerCase().contains("operations")) {
        post.addHeader("x-ms-version", "2014-02-01");
      } else if (url.toLowerCase().contains("/deployments")) {
        post.addHeader("x-ms-version", "2014-05-01");
      } else {
        post.addHeader("x-ms-version", "2012-03-01");
      }

      if (strategy != null && strategy.getSendAsHeader()) {
        post.addHeader(strategy.getHeaderName(), strategy.getRequestId());
      }

      // If it is networking configuration services
      if (url.endsWith("/services/networking/media")) {
        post.addHeader("Content-Type", "text/plain;charset=UTF-8");
      } else {
        post.addHeader("Content-Type", "application/xml;charset=UTF-8");
      }

      if (wire.isDebugEnabled()) {
        wire.debug(post.getRequestLine().toString());
        for (Header header : post.getAllHeaders()) {
          wire.debug(header.getName() + ": " + header.getValue());
        }
        wire.debug("");
        if (body != null) {
          wire.debug(body);
          wire.debug("");
        }
      }
      if (body != null) {
        try {
          if (url.endsWith("/services/networking/media")) {
            post.setEntity(new StringEntity(body, "text/plain", "utf-8"));
          } else {
            post.setEntity(new StringEntity(body, "application/xml", "utf-8"));
          }

        } catch (UnsupportedEncodingException e) {
          throw new InternalException(e);
        }
      }
      HttpResponse response;
      StatusLine status;

      try {
        response = client.execute(post);
        status = response.getStatusLine();
      } catch (IOException e) {
        logger.error(
            "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
        if (logger.isTraceEnabled()) {
          e.printStackTrace();
        }
        throw new CloudException(e);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("post(): HTTP Status " + status);
      }
      Header[] headers = response.getAllHeaders();

      if (wire.isDebugEnabled()) {
        wire.debug(status.toString());
      }
      for (Header h : headers) {
        if (h.getValue() != null) {
          if (wire.isDebugEnabled()) {
            wire.debug(h.getName() + ": " + h.getValue().trim());
          }
          if (h.getName().equalsIgnoreCase("x-ms-request-id")) {
            requestId = h.getValue().trim();
          }
        } else {
          if (wire.isDebugEnabled()) {
            wire.debug(h.getName() + ":");
          }
        }
      }
      if (wire.isDebugEnabled()) {
        wire.debug("");
      }

      if (status.getStatusCode() != HttpServletResponse.SC_OK
          && status.getStatusCode() != HttpServletResponse.SC_CREATED
          && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
        logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

        HttpEntity entity = response.getEntity();

        if (entity == null) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              "An error was returned without explanation");
        }
        try {
          body = EntityUtils.toString(entity);
        } catch (IOException e) {
          throw new AzureException(
              CloudErrorType.GENERAL,
              status.getStatusCode(),
              status.getReasonPhrase(),
              e.getMessage());
        }
        if (wire.isDebugEnabled()) {
          wire.debug(body);
        }
        wire.debug("");
        AzureException.ExceptionItems items =
            AzureException.parseException(status.getStatusCode(), body);

        if (items == null) {
          throw new CloudException(
              CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
        }
        logger.error(
            "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
        throw new AzureException(items);
      }
    } finally {
      if (logger.isTraceEnabled()) {
        logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
      }
      if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(
            "POST --------------------------------------------------------> "
                + endpoint
                + account
                + resource);
      }
    }
    return requestId;
  }
Ejemplo n.º 29
-52
    @Override
    protected String[] doInBackground(String... parms) {
      String[] resultarr = new String[1];
      String intentstr = parms[0];

      // int count = urls.length;
      // long totalSize = 0; for (int i = 0; i < count; i++) { totalSize +=
      // Downloader.downloadFile(urls[i]);
      // publishProgress((int) ((i / (float) count) * 100));
      // Escape early if cancel() is called
      // if (isCancelled())
      //		break;

      try {
        // Connect to API and authenticate
        publishProgress("Connecting and authenticating API session...");

        ApiWrapper wrapper;
        // wrapper = Api.wrapper;
        wrapper = new ApiWrapper(Api.mClientID, Api.mClientSecret, null, null);
        wrapper.login("un1tz3r0", "Farscap3");

        publishProgress("Resolving url...");

        String resolvedurl = resolveURL(wrapper, intentstr);

        publishProgress("Getting metadata...");

        HttpResponse resp = wrapper.get(Request.to(resolvedurl));

        JSONObject jso = Http.getJSON(resp);
        // resultstr = jso.toString();

        if (jso.getString("kind").equals("track")) {
          if (jso.getBoolean("downloadable")) {
            publishProgress("Getting download redirect URL...");

            String dlrurl =
                wrapper
                    .getURI(
                        Request.to(jso.getString("download_url")).add("allow_redirect", false),
                        false,
                        false)
                    .toString();
            HttpResponse dlrresp = wrapper.get(Request.to(dlrurl));
            String dlstr = dlrurl;
            if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
              Header dlloch = dlrresp.getFirstHeader("location");
              if ((dlloch == null) || (dlloch.getValue() == null))
                throw new RuntimeException("Download url HEAD response has no location header");

              dlstr = wrapper.getURI(Request.to(dlloch.getValue()), false, false).toString();
            } else if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
              dlstr = dlrurl;
            } else {
              throw new RuntimeException(
                  "Download url HEAD response has wrong status ("
                      + String.valueOf(dlrresp.getStatusLine().getStatusCode())
                      + " "
                      + dlrresp.getStatusLine().getReasonPhrase()
                      + ")");
            }
            // String dlstr = Request.to( dlloch.getValue() ).add("CLIENT_ID",
            // Api.mClientID).toString();

            //												if(dlresp2.getStatusLine().getStatusCode() !=
            // HttpStatus.SC_MOVED_TEMPORARILY)
            //														throw new RuntimeException("Download redirect url HEAD response has
            // wrong status: " + dlresp2.getStatusLine().toString());
            //												Header dlloc2 = dlresp2.getFirstHeader("location");
            //												if((dlloc2 == null) || (dlloc2.getValue() == null))
            //														throw new RuntimeException("Download redirect url HEAD response has no
            // location header");
            //

            resultarr = new String[2];
            resultarr[1] =
                jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "")
                    + "."
                    + jso.getString("original_format");
            resultarr[0] = dlstr;
          } else {
            Stream st = wrapper.resolveStreamUrl(jso.getString("stream_url"), true);
            resultarr = new String[2];
            resultarr[1] = jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "").concat(".mp3");
            resultarr[0] = st.streamUrl;
          }
        }
      } catch (JSONException e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      } catch (IOException e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      } catch (Exception e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      }

      return resultarr;
    }