コード例 #1
0
 @Override
 public void run() {
   if (!httpRequest.isAborted()) {
     httpRequestAborted = true;
     httpRequest.abort();
   }
 }
コード例 #2
0
  private HttpResponse getHTTPResponse() throws IOException, NullPointerException {
    if (fileURI == null) throw new NullPointerException("No file URI specified");

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    // Clear down the local cookie store every time to make sure we don't have any left over cookies
    // influencing the test
    localContext.setAttribute(ClientContext.COOKIE_STORE, null);

    LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState);
    if (mimicWebDriverCookieState) {
      localContext.setAttribute(
          ClientContext.COOKIE_STORE, mimicCookieState(driver.manage().getCookies()));
    }

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);
    HttpParams httpRequestParameters = requestMethod.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    requestMethod.setParams(httpRequestParameters);
    // TODO if post send map of variables, also need to add a post map setter

    LOG.info("Sending " + httpRequestMethod.toString() + " request for: " + fileURI);
    return client.execute(requestMethod, localContext);
  }
コード例 #3
0
ファイル: HttpManager.java プロジェクト: corezoid/sdk-java
 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();
   }
 }
コード例 #4
0
  @Override
  public final HttpResponse invoke(Q query, String endpoint) throws InvocationException {
    Preconditions.checkNotNull(query);
    Preconditions.checkNotNull(endpoint);

    HttpRequestBase method = null;
    HttpEntity response = null;
    try {
      method = getHttpMethod(query, endpoint);
      method.setParams(getHttpClientParams(query));

      org.apache.http.HttpResponse httpResponse = httpClient.execute(method);
      response = httpResponse.getEntity();
      return HttpResponse.create(
          httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(response));
    } catch (Exception e) {
      if (method != null) {
        log.debug(
            "Error during invocation with URL: "
                + method.getURI()
                + ", endpoint: "
                + endpoint
                + ", query: "
                + query,
            e);
      } else {
        log.debug("Error during invocation with: endpoint: " + endpoint + ", query: " + query, e);
      }
      throw new InvocationException("InvocationException : ", e);
    } finally {
      EntityUtils.consumeQuietly(response);
    }
  }
コード例 #5
0
 protected RetsHttpResponse execute(final HttpRequestBase method, Map<String, String> headers)
     throws RetsException {
   try {
     // add the default headers
     if (this.defaultHeaders != null) {
       for (Map.Entry<String, String> entry : this.defaultHeaders.entrySet()) {
         method.setHeader(entry.getKey(), entry.getValue());
       }
     }
     // add our request headers from rets
     if (headers != null) {
       for (Map.Entry<String, String> entry : headers.entrySet()) {
         method.setHeader(entry.getKey(), entry.getValue());
       }
     }
     // optional ua-auth stuff here
     if (this.userAgentPassword != null) {
       method.setHeader(RETS_UA_AUTH_HEADER, calculateUaAuthHeader(method, getCookies()));
     }
     // try to execute the request
     HttpResponse response = this.httpClient.execute(method);
     StatusLine status = response.getStatusLine();
     if (status.getStatusCode() != HttpStatus.SC_OK) {
       throw new InvalidHttpStatusException(status);
     }
     return new CommonsHttpClientResponse(response, getCookies());
   } catch (Exception e) {
     throw new RetsException(e);
   }
 }
コード例 #6
0
  private static String apiCall(HttpRequestBase method) throws NetworkErrorException {

    Log.d("apiCall()", method.getURI().toString());
    String response = null;
    method.setHeader("User-Agent", "ANDROID DEBUG DEVICE");
    try {

      try {
        try {
          response = httpClient.execute(method, new BasicResponseHandler());
        } catch (IllegalStateException e) {
          throw new NetworkErrorException("404");
        }
        Log.d(TAG, response);
      } catch (HttpResponseException e) {
        Log.d(TAG, Integer.toString(e.getStatusCode()));
        throw new NetworkErrorException(Integer.toString(e.getStatusCode()));
      }

    } catch (IOException e) {
      Log.d(TAG, "IO");
      throw new NetworkErrorException("404");
    }
    Log.d("odpowiedz: ", response);
    return response;
  }
コード例 #7
0
 public static HttpRequest buildFreeRequest(HttpRequest request) {
   if (request instanceof HttpRequestBase) {
     HttpRequestBase httpRequestBase = (HttpRequestBase) request;
     httpRequestBase.setURI(generateFreeURI(httpRequestBase.getURI()));
   }
   return request;
 }
コード例 #8
0
  private void writeLinks(HttpRequestBase httpMethod, String basePath) {
    StringBuilder linkHeader = new StringBuilder();

    for (RiakLink link : this.links) {
      if (linkHeader.length() > 0) {
        linkHeader.append(", ");
      }
      linkHeader.append("<");
      linkHeader.append(basePath);
      linkHeader.append("/");
      linkHeader.append(link.getBucket());
      linkHeader.append("/");
      linkHeader.append(link.getKey());
      linkHeader.append(">; ");
      linkHeader.append(Constants.LINK_TAG);
      linkHeader.append("=\"");
      linkHeader.append(link.getTag());
      linkHeader.append("\"");

      // To avoid (MochiWeb) problems with too long headers, flush if
      // it grows too big:
      if (linkHeader.length() > 2000) {
        httpMethod.addHeader(Constants.HDR_LINK, linkHeader.toString());
        linkHeader = new StringBuilder();
      }
    }
    if (linkHeader.length() > 0) {
      httpMethod.addHeader(Constants.HDR_LINK, linkHeader.toString());
    }
  }
コード例 #9
0
 @Override
 protected void authenticate(IOperationMonitor monitor) throws IOException {
   UserCredentials credentials =
       getClient().getLocation().getCredentials(AuthenticationType.REPOSITORY);
   if (credentials == null) {
     throw new IllegalStateException("Authentication requested without valid credentials");
   }
   HttpRequestBase request =
       new HttpGet(
           baseUrl()
               + MessageFormat.format(
                   "/login?login={0}&password={1}",
                   new Object[] {credentials.getUserName(), credentials.getPassword()}));
   request.setHeader(CONTENT_TYPE, TEXT_XML_CHARSET_UTF_8);
   request.setHeader(ACCEPT, APPLICATION_JSON);
   HttpResponse response = getClient().execute(request, monitor);
   try {
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
       getClient().setAuthenticated(false);
       throw new AuthenticationException(
           "Authentication failed",
           new AuthenticationRequest<AuthenticationType<UserCredentials>>(
               getClient().getLocation(), AuthenticationType.REPOSITORY));
     } else {
       TypeToken<LoginToken> type = new TypeToken<LoginToken>() {};
       InputStream is = response.getEntity().getContent();
       InputStreamReader in = new InputStreamReader(is);
       LoginToken loginToken = new Gson().fromJson(in, type.getType());
       ((BugzillaRestHttpClient) getClient()).setLoginToken(loginToken);
       getClient().setAuthenticated(true);
     }
   } finally {
     HttpUtil.release(request, response, monitor);
   }
 }
コード例 #10
0
ファイル: JobClient.java プロジェクト: prasincs/Cook
 /**
  * Abort jobs for a given list of job {@link UUID}s. If the size of the list is larger that the
  * {@code _batchRequestSize}, it will partition the list into smaller lists to abort separately.
  *
  * @param uuids specifies a list of job {@link UUID}s expected to abort.
  * @throws JobClientException
  */
 public void abort(Collection<UUID> uuids) throws JobClientException {
   final List<NameValuePair> allParams = new ArrayList<NameValuePair>(uuids.size());
   for (UUID uuid : uuids) {
     allParams.add(new BasicNameValuePair("job", uuid.toString()));
   }
   // Partition a large query into small queries.
   for (final List<NameValuePair> params : Lists.partition(allParams, _batchRequestSize)) {
     HttpRequestBase httpRequest;
     try {
       URIBuilder uriBuilder = new URIBuilder(_uri);
       uriBuilder.addParameters(params);
       httpRequest = new HttpDelete(uriBuilder.build());
     } catch (URISyntaxException e) {
       throw releaseAndCreateException(
           null, "Can not submit DELETE request " + params + " via uri " + _uri, e);
     }
     HttpResponse httpResponse;
     try {
       httpResponse = _httpClient.execute(httpRequest);
     } catch (IOException e) {
       throw releaseAndCreateException(
           httpRequest, "Can not submit DELETE request " + params + " via uri " + _uri, e);
     }
     // Check status code.
     final StatusLine statusLine = httpResponse.getStatusLine();
     // Base on the decision graph
     // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
     // If jobs are aborted successfully, the returned status code is 204.
     if (statusLine.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
       throw releaseAndCreateException(
           httpRequest,
           "The response of DELETE request "
               + params
               + " via uri "
               + _uri
               + ": "
               + statusLine.getReasonPhrase()
               + ", "
               + statusLine.getStatusCode(),
           null);
     }
     // Parse the response.
     try {
       // Parse the response to string.
       final HttpEntity entity = httpResponse.getEntity();
       if (null != entity) {
         final String response = EntityUtils.toString(entity);
         if (_log.isDebugEnabled()) {
           _log.debug("Response String for aborting jobs " + uuids + " is " + response);
         }
       }
     } catch (ParseException | IOException e) {
       throw new JobClientException(
           "Can not parse the response for DELETE request " + params + " via uri " + _uri, e);
     } finally {
       httpRequest.releaseConnection();
     }
   }
 }
コード例 #11
0
ファイル: HTTP.java プロジェクト: ChrisCinelli/native-android
  public Response makeRequest(
      Methods method, URI uri, HashMap<String, String> requestHeaders, String data) {

    HttpRequestBase request = null;

    try {
      if (method == Methods.GET) {
        request = new HttpGet();
      } else if (method == Methods.POST) {
        request = new HttpPost();
        if (data != null) {
          ((HttpPost) request).setEntity(new StringEntity(data, "UTF-8"));
        }
      } else if (method == Methods.PUT) {
        request = new HttpPut();
        if (data != null) {
          ((HttpPut) request).setEntity(new StringEntity(data, "UTF-8"));
        }
      } else if (method == Methods.DELETE) {
        request = new HttpDelete();
      }
    } catch (UnsupportedEncodingException e) {
      logger.log(e);
    }
    request.setURI(uri);
    AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
    if (requestHeaders != null) {
      for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
        request.addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
      }
    }

    HttpResponse response = null;
    Response retVal = new Response();
    retVal.headers = new HashMap<String, String>();
    try {
      response = client.execute(request);
    } catch (SocketTimeoutException e) {
      // forget it--we don't care that the user couldn't connect
      // TODO hand this back as an error to JS
    } catch (IOException e) {
      if (!caughtIOException) {
        caughtIOException = true;
        logger.log(e);
      }
    } catch (Exception e) {
      logger.log(e);
    }
    if (response != null) {
      retVal.status = response.getStatusLine().getStatusCode();
      retVal.body = readContent(response);
      for (Header header : response.getAllHeaders()) {
        retVal.headers.put(header.getName(), header.getValue());
      }
    }
    client.close();
    return retVal;
  }
コード例 #12
0
  /**
   * Performs the request constructed in this builder and returns the response
   *
   * @return the repository response
   * @throws FcrepoOperationFailedException when the underlying HTTP request results in an error
   */
  public FcrepoResponse perform() throws FcrepoOperationFailedException {
    LOGGER.debug(
        "Fcrepo {} request to {} with headers: {}",
        request.getMethod(),
        targetUri,
        request.getAllHeaders());

    return client.executeRequest(targetUri, request);
  }
コード例 #13
0
ファイル: Vimeo.java プロジェクト: UrfiFeru/PublicVideos
 private static ArrayList<SearchResults> apiRequest(
     String endpoint, String methodName, Map<String, String> params, File file)
     throws IOException, JSONException {
   HttpClient client = new DefaultHttpClient();
   HttpRequestBase request = null;
   String url = null;
   if (endpoint.startsWith("http")) {
     url = endpoint;
   } else {
     url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString();
   }
   if (methodName.equals(HttpGet.METHOD_NAME)) {
     request = new HttpGet(url);
   } else if (methodName.equals(HttpPost.METHOD_NAME)) {
     request = new HttpPost(url);
   }
   request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2");
   request.addHeader(
       "Authorization", new StringBuffer(tokenType).append(" ").append(token).toString());
   HttpResponse response = client.execute(request);
   String responseAsString = null;
   int statusCode = response.getStatusLine().getStatusCode();
   if (statusCode != 204) {
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     response.getEntity().writeTo(out);
     responseAsString = out.toString("UTF-8");
     out.close();
   }
   JSONObject json = null;
   try {
     json = new JSONObject(responseAsString);
   } catch (Exception e) {
     json = new JSONObject();
   }
   ArrayList<SearchResults> tempSearch = new ArrayList<SearchResults>();
   for (int i = 0; i < json.getJSONArray("data").length(); i++) {
     JSONObject object = (JSONObject) json.getJSONArray("data").get(i);
     Map<String, String> out = new HashMap<String, String>();
     parse(object, out);
     SearchResults temp = new SearchResults();
     temp.setTitle(out.get("name"));
     //			temp.setOwner("By: " + out.get("owner.screenname"));
     temp.setId(out.get("uri").substring(out.get("uri").lastIndexOf('/') + 1));
     JSONArray tJson = new JSONArray(out.get("sizes"));
     for (int j = 0; j < tJson.length(); j++) {
       parse((JSONObject) tJson.get(j), out);
       if (out.get("width").equals("200")) {
         temp.setThumbnailUrl(out.get("link"));
         break;
       }
     }
     temp.setProvider("Vimeo");
     tempSearch.add(temp);
   }
   return tempSearch;
 }
コード例 #14
0
 private HttpRequestBase getDefaultMethod(String paramString1, ArrayList<BasicNameValuePair> paramArrayList, String paramString2)
   throws FabException
 {
   Object localObject;
   try
   {
     StringBuilder localStringBuilder;
     String[] arrayOfString;
     int i;
     int j;
     if (paramString2.equalsIgnoreCase("POST"))
     {
       localObject = new HttpPost(new URI(paramString1));
       ((HttpRequestBase)localObject).setHeader("Content-type", "application/x-www-form-urlencoded");
       ((HttpRequestBase)localObject).setHeader("User-Agent", "Android");
       if (!TextUtils.isEmpty(FabSharedPrefs.getFabCookies()))
       {
         localStringBuilder = new StringBuilder();
         arrayOfString = FabSharedPrefs.getFabCookies().split("<==>");
         i = 0;
         j = arrayOfString.length;
       }
     }
     while (true)
     {
       if (i >= j)
       {
         ((HttpRequestBase)localObject).setHeader("Cookie", localStringBuilder.toString());
         if ((!TextUtils.isEmpty(FabEnvironment.reqAuth())) && (paramString1.contains(FabEnvironment.baseDomain())))
           ((HttpRequestBase)localObject).setHeader("Authorization", FabEnvironment.reqAuth());
         if ((paramArrayList == null) || (paramArrayList.isEmpty()))
           break label275;
         ((HttpPost)localObject).setEntity(new UrlEncodedFormEntity(paramArrayList, "UTF-8"));
         break label275;
         if (paramString2.equalsIgnoreCase("GET"))
         {
           localObject = new HttpGet(new URI(paramString1));
           break;
         }
         localObject = new HttpGet(new URI(paramString1));
         break;
       }
       localStringBuilder.append(arrayOfString[i].split("<@@>")[0] + "; ");
       i++;
     }
   }
   catch (URISyntaxException localURISyntaxException)
   {
     throw new FabException(localURISyntaxException);
   }
   catch (Exception localException)
   {
     throw new FabException(localException);
   }
   label275: return localObject;
 }
コード例 #15
0
ファイル: AbstractHttpApi.java プロジェクト: rbyyy/mycodesvn
 /**
  * execute() an httpRequest catching exceptions and returning null instead.
  *
  * @param httpRequest
  * @return
  * @throws IOException
  */
 public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException {
   if (DEBUG) LOG.log(Level.FINE, "executing HttpRequest for: " + httpRequest.getURI().toString());
   try {
     mHttpClient.getConnectionManager().closeExpiredConnections();
     return mHttpClient.execute(httpRequest);
   } catch (IOException e) {
     httpRequest.abort();
     throw e;
   }
 }
コード例 #16
0
  @Override
  public boolean matchesSafely(HttpRequestBase method) {
    boolean matches = true;
    if (type != null) {
      switch (type) {
        case GET:
          matches &= method instanceof HttpGet;
          break;
        case POST:
          matches &= method instanceof HttpPost;
          break;
        default:
          break;
      }
    }

    if (url != null) {
      try {
        matches &= url.equals(method.getURI().toString());
      } catch (Exception e) {
        Assert.fail();
      }
    }

    if (urlPattern != null) {
      try {
        matches &= urlPattern.matcher(method.getURI().toString()).matches();
      } catch (Exception e) {
        Assert.fail();
      }
    }

    if (method instanceof HttpPost) {
      HttpPost postMethod = (HttpPost) method;
      HttpEntity entity = postMethod.getEntity();
      if (entity instanceof StringEntity) {
        String content = "";
        try {
          content = IOUtils.toString(((StringEntity) entity).getContent());
        } catch (IOException e) {
          e.printStackTrace();
          return false;
        }
        if (postBody != null) {
          matches &= postBody.equals(content);
        }

        if (postBodyPattern != null) {
          matches &= postBodyPattern.matcher(content).matches();
        }
      }
    }
    return matches;
  }
コード例 #17
0
  public Response request(String url, String data, String method) {
    WorkerThread th = (WorkerThread) Thread.currentThread();

    HttpRequestBase req;
    if (method == "POST") {
      req = new HttpPost(url);
      if (data != null) {
        StringEntity se = null;
        try {
          se = new StringEntity(data);
        } catch (UnsupportedEncodingException e) {
          return new Response(-1, e.toString(), null);
        }
        se.setContentType("application/x-www-form-urlencoded");
        ((HttpPost) req).setEntity(se);
      }
    } else {
      req = new HttpGet(url);
    }
    req.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpResponse response = null;
    try {
      response = th.client.execute(req);
    } catch (Exception e) {
      return new Response(-1, e.toString(), null);
    }

    StatusLine statusLine = response.getStatusLine();
    String responseData = null;
    try {
      InputStream is = response.getEntity().getContent();
      try {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
          sb.append(line);
        }
        responseData = sb.toString();
      } finally {
        is.close();
      }
    } catch (Exception e) {
      return new Response(-1, e.toString(), null);
    }

    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
      return new Response(200, null, responseData);
    }
    return new Response(statusLine.getStatusCode(), statusLine.getReasonPhrase(), null);
  }
コード例 #18
0
ファイル: ConsumeREST.java プロジェクト: acsdev/articles
  @Override
  protected String doInBackground(String... params) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpRequestBase httpRequest = null;

    if (METHOD_NAME[0].equals(params[0])) {

      httpRequest = new HttpGet(URL.concat(METHOD_NAME[0]).concat("/51250652006"));
      httpRequest.setHeader("Content-type", "application/json");

    } else if (METHOD_NAME[1].equals(params[0])) {

      httpRequest = new HttpPost(URL.concat(METHOD_NAME[1]));
      httpRequest.setHeader("Content-type", "application/json");

      try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cpf", "51250652006");
        jsonObject.put("nome", "Uguinho");
        jsonObject.put("dataNascimento", "1986-05-14"); // PESQUISAR
        // DATEFORMATE
        // JERSEY

        ((HttpPost) httpRequest)
            .setEntity(new ByteArrayEntity(jsonObject.toString().getBytes("UTF8")));

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

    } else if (METHOD_NAME[2].equals(params[0])) {

      httpRequest = new HttpGet(URL.concat(METHOD_NAME[2]));
      httpRequest.setHeader("Content-type", "application/json");
    }

    try {

      HttpResponse response = httpClient.execute(httpRequest);

      Log.i("ConsumeRESTAsyncTask", StreamToString.doIt(response.getEntity().getContent()));
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
コード例 #19
0
  public HttpResponse execute(DefaultHttpClient client, HttpRequestBase method, PrintStream logger)
      throws IOException {
    doSecurity(client, method.getURI());

    logger.println("Sending request to url: " + method.getURI());
    final HttpResponse execute = client.execute(method);
    logger.println("Response Code: " + execute.getStatusLine());
    logger.println("Response: \n" + EntityUtils.toString(execute.getEntity()));

    EntityUtils.consume(execute.getEntity());

    return execute;
  }
コード例 #20
0
 public void testAddHeaders() {
   HttpRequestBase method = new HttpPost();
   EasSyncService svc = new EasSyncService();
   svc.mAuthString = "auth";
   svc.mProtocolVersion = "12.1";
   svc.mAccount = null;
   // With second argument false, there should be no header
   svc.setHeaders(method, false);
   Header[] headers = method.getHeaders("X-MS-PolicyKey");
   assertEquals(0, headers.length);
   // With second argument true, there should always be a header
   // The value will be "0" without an account
   method.removeHeaders("X-MS-PolicyKey");
   svc.setHeaders(method, true);
   headers = method.getHeaders("X-MS-PolicyKey");
   assertEquals(1, headers.length);
   assertEquals("0", headers[0].getValue());
   // With an account, but null security key, the header's value should be "0"
   Account account = new Account();
   account.mSecuritySyncKey = null;
   svc.mAccount = account;
   method.removeHeaders("X-MS-PolicyKey");
   svc.setHeaders(method, true);
   headers = method.getHeaders("X-MS-PolicyKey");
   assertEquals(1, headers.length);
   assertEquals("0", headers[0].getValue());
   // With an account and security key, the header's value should be the security key
   account.mSecuritySyncKey = "key";
   svc.mAccount = account;
   method.removeHeaders("X-MS-PolicyKey");
   svc.setHeaders(method, true);
   headers = method.getHeaders("X-MS-PolicyKey");
   assertEquals(1, headers.length);
   assertEquals("key", headers[0].getValue());
 }
コード例 #21
0
  @Test
  public void shouldBeAbleToLoadHttpMethod() throws Exception {

    headers.header("header1", "value1");

    HttpRequestBase httpMethod = new HttpGet(uri);
    engine.loadHttpMethod(request, httpMethod);

    Header[] headers = httpMethod.getAllHeaders();

    assertEquals(1, headers.length);
    assertEquals("header1", headers[0].getName());
    assertEquals("value1", headers[0].getValue());
  }
コード例 #22
0
 public void addRequestHeaders(NativeObject headersNO) {
   if (headersNO != null) {
     for (Object o : headersNO.getAllIds()) {
       Object val = headersNO.get(o.toString(), null);
       if (val instanceof NativeArray) {
         NativeArray arr = (NativeArray) val;
         for (int i = 0; i < arr.getLength(); i++) {
           method.addHeader(o.toString(), arr.get(i, null).toString());
         }
       } else {
         method.addHeader(o.toString(), val.toString());
       }
     }
   }
 }
コード例 #23
0
  protected String execute(HttpRequestBase httpRequestBase)
      throws CredentialException, IOException {

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {
      if (_closeableHttpClient == null) {
        afterPropertiesSet();
      }

      HttpResponse httpResponse = _closeableHttpClient.execute(httpHost, httpRequestBase);

      StatusLine statusLine = httpResponse.getStatusLine();

      if (statusLine.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {

        if (_logger.isWarnEnabled()) {
          _logger.warn("Status code " + statusLine.getStatusCode());
        }

        return null;
      } else if (statusLine.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {

        throw new CredentialException("Not authorized to access JSON web service");
      } else if (statusLine.getStatusCode() == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {

        throw new JSONWebServiceUnavailableException("Service unavailable");
      }

      return EntityUtils.toString(httpResponse.getEntity(), Charsets.UTF_8);
    } finally {
      httpRequestBase.releaseConnection();
    }
  }
コード例 #24
0
  private Response doRequest(final Request<?> request, final HttpRequestBase fetcher) {
    if (fetcher == null) {
      return null;
    }

    List<Parameter> headers = request.getHeaders();
    if (checkListOfParams(headers)) {
      for (Parameter parameter : headers) {
        Header header = new BasicHeader(parameter.getName(), parameter.getValue());
        fetcher.addHeader(header);
      }
    }

    final DefaultHttpClient httpClient = getHttpClient();
    List<Parameter> cookies = request.getCookies();
    if (checkListOfParams(cookies)) {
      CookieStore cookieStore = httpClient.getCookieStore();
      for (Parameter cookie : cookies) {
        cookieStore.addCookie(new BasicClientCookie(cookie.getName(), cookie.getValue()));
      }
      httpClient.setCookieStore(cookieStore);
    }

    return doRequest(fetcher, httpClient);
  }
コード例 #25
0
 @Override
 public synchronized void abortCurrentRequest() {
   if (currentRequest != null) {
     currentRequest.abort();
     currentRequest = null;
   }
 }
コード例 #26
0
  @Override
  public void onCheckRequestHeaders(String requestUrl, HttpRequestBase request) {
    if (request == null) {
      throw new IllegalArgumentException("Http Request is null");
    }

    if (SUPPORT_RANGED) {
      // 目前只有大文件下载才会做此接口回调,在此回调中可以增加断点续传
      if (request instanceof HttpGet) {
        String saveFile =
            mDownloadFilenameCreateListener != null
                ? mDownloadFilenameCreateListener.onFilenameCreateWithDownloadUrl(requestUrl)
                : mDefaultDownloadFilenameCreateListener.onFilenameCreateWithDownloadUrl(
                    requestUrl);
        File bigCacheFile = new File(INPUT_STREAM_CACHE_PATH);
        if (!bigCacheFile.exists() || !bigCacheFile.isDirectory()) {
          bigCacheFile.delete();
          bigCacheFile.mkdirs();
        }

        File tempFile = new File(INPUT_STREAM_CACHE_PATH + saveFile);
        long fileSize = 0;
        if (tempFile.exists()) {
          fileSize = tempFile.length();
        } else {
          fileSize = 0;
        }

        request.addHeader("RANGE", "bytes=" + fileSize + "-");
      }
    }
  }
コード例 #27
0
 public static HttpRequestBase buildHeaders(
     HttpRequestBase httpRequestBase, Map<String, String> headers) {
   for (Entry<String, String> header : headers.entrySet()) {
     httpRequestBase.setHeader(header.getKey(), header.getValue());
   }
   return httpRequestBase;
 }
コード例 #28
0
  @Test
  public void GetRequest()
      throws URISyntaxException, ClientProtocolException, IOException, ParserConfigurationException,
          UnsupportedOperationException, SAXException {
    HttpUriRequest request = new HttpGet(url);
    URIBuilder uri = new URIBuilder(request.getURI()).addParameter("CountryName", country);
    ((HttpRequestBase) request).setURI(uri.build());

    // Testing headers
    HttpResponse response = client.execute(request);
    Header[] headers = response.getAllHeaders();
    for (Header head : headers) {
      System.out.println(head.getName() + "---" + head.getValue());
    }
    System.out.println("================================================");

    // Testing response
    // parsing xml
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(response.getEntity().getContent());

    // Printing root
    doc.getDocumentElement().normalize();
    NodeList nList = doc.getElementsByTagName("string");
    Node aNode = nList.item(0);
    Element element = (Element) aNode;
    System.out.println(element.getFirstChild());
  }
コード例 #29
0
ファイル: FinalHttp.java プロジェクト: newisso/afinal
 private static void abortConnection(final HttpRequestBase hrb, final HttpClient httpclient) {
   if (hrb != null) {
     hrb.abort();
   }
   if (httpclient != null) {
     httpclient.getConnectionManager().shutdown();
   }
 }
コード例 #30
0
  private void addHeaders(HttpClientRequest request, HttpRequestBase baseRequest) {
    ScopedAttributesResolutionStrategy attributes =
        request.getAttributes().getScopeAttributeContext(ContextScope.REQUEST_HEADERS);

    for (Attribute attribute : attributes) {
      baseRequest.addHeader(attribute.getName(), attribute.getValue(String.class));
    }
  }