Пример #1
0
  @RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST)
  public String formSubmit(@ModelAttribute User user, Model model)
      throws MalformedURLException, IOException {
    model.addAttribute("user", user);
    HttpPost post =
        new HttpPost(
            "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/");
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName()));
    nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName()));
    nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
    nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
    nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation()));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(post);
    response = httpclient.execute(post);
    System.out.println("Status code is " + response.getStatusLine().getStatusCode());
    System.out.println(response.toString());
    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++");
    System.out.println(response.getFirstHeader("Location"));
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    EntityUtils.consume(response.getEntity());

    /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html");
    FileWriter fileWriter = new FileWriter(newTextFile);
    fileWriter.write(response.toString());
    fileWriter.close();*/
    return "result";
  }
Пример #2
0
 public void testConsumeContent() throws Exception {
   String s = "Message content";
   StringEntity httpentity = new StringEntity(s);
   HttpEntityWrapper wrapped = new HttpEntityWrapper(httpentity);
   EntityUtils.consume(wrapped);
   EntityUtils.consume(wrapped);
 }
Пример #3
0
  private static void login(Client httpclient) {
    if (loggedin) return;
    log.debug("Attempting login");
    try {
      HttpResponse response = httpclient.get(loginUri);
      EntityUtils.consume(response.getEntity());
      log.debug(response);

      ClientParam[] nvps =
          new ClientParam[] {
            new StringParam("action", "login"),
            new StringParam("retard_protection", "1"),
            new StringParam("name", props.getProperty("user")),
            new StringParam("pass", props.getProperty("pass")),
            new StringParam("login", "Login to&nbsp;FurAffinity")
          };

      response =
          httpclient.post(loginPostUri, loginHeaders, nvps, Client.PostDataType.UrlEncoded, null);
      HttpEntity entity = response.getEntity();
      EntityUtils.consume(entity);
    } catch (Exception e) {
      log.error("Could not log in", e);
    }
  }
  @Test
  public void testBasicAuthenticationCredentialsCaching() throws Exception {
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("test", "test"));

    TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy();

    this.httpclient.setCredentialsProvider(credsProvider);
    this.httpclient.setTargetAuthenticationStrategy(authStrategy);

    HttpContext context = new BasicHttpContext();

    HttpHost targethost = getServerHttp();
    HttpGet httpget = new HttpGet("/");

    HttpResponse response1 = this.httpclient.execute(targethost, httpget, context);
    HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    HttpResponse response2 = this.httpclient.execute(targethost, httpget, context);
    HttpEntity entity2 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity2);
    EntityUtils.consume(entity2);

    Assert.assertEquals(1, authStrategy.getCount());
  }
Пример #5
0
  public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();

      System.out.println("Login form get: " + response.getStatusLine());
      EntityUtils.consume(entity);

      System.out.println("Initial set of cookies:");
      List<Cookie> cookies = httpclient.getCookieStore().getCookies();
      if (cookies.isEmpty()) {
        System.out.println("None");
      } else {
        for (int i = 0; i < cookies.size(); i++) {
          System.out.println("- " + cookies.get(i).toString());
        }
      }

      HttpPost httpost =
          new HttpPost(
              "https://portal.sun.com/amserver/UI/Login?"
                  + "org=self_registered_users&"
                  + "goto=/portal/dt&"
                  + "gotoOnFail=/portal/dt?error=true");

      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      nvps.add(new BasicNameValuePair("IDToken1", "username"));
      nvps.add(new BasicNameValuePair("IDToken2", "password"));

      httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

      response = httpclient.execute(httpost);
      entity = response.getEntity();

      System.out.println("Login form get: " + response.getStatusLine());
      EntityUtils.consume(entity);

      System.out.println("Post logon cookies:");
      cookies = httpclient.getCookieStore().getCookies();
      if (cookies.isEmpty()) {
        System.out.println("None");
      } else {
        for (int i = 0; i < cookies.size(); i++) {
          System.out.println("- " + cookies.get(i).toString());
        }
      }

    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
    }
  }
  public void testSOAPCall() throws Exception {

    // test with a valid request
    HttpPost httppost = new HttpPost("http://localhost:8280/service/soap-proxy-1");
    httppost.setEntity(new StringEntity(getQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    HttpResponse response = client.execute(httppost);
    EntityUtils.consume(response.getEntity());
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    // test with a malformed XML
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-1");
    httppost.setEntity(new StringEntity(malformedGetQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(
        HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode());
    Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("Validation Failed"));

    // test with a request violating schema
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-1");
    httppost.setEntity(new StringEntity(invalidQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(
        HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode());
    Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("Validation Failed"));

    // test with CBR
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-2");
    httppost.setEntity(new StringEntity(getQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    // test with CBR for a failure case
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-2");
    httppost.setEntity(new StringEntity(validQuoteRequestACP, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(
        HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode());
    String responseContent = EntityUtils.toString(response.getEntity());
    System.out.println("==>" + responseContent);
    Assert.assertTrue(
        responseContent.contains(
            "Endpoint stockquote-err failed, with error code 101503 : Connect attempt to server failed"));
  }
  @Test
  public void testKeepAlive() throws Exception {
    String url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/pin/a14";

    HttpPut request = new HttpPut(url);
    request.setHeader("Connection", "keep-alive");

    HttpGet getRequest = new HttpGet(url);
    getRequest.setHeader("Connection", "keep-alive");

    for (int i = 0; i < 100; i++) {
      request.setEntity(new StringEntity("[\"" + i + "\"]", ContentType.APPLICATION_JSON));

      try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());
      }

      try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) {
        assertEquals(200, response2.getStatusLine().getStatusCode());
        List<String> values = consumeJsonPinValues(response2);
        assertEquals(1, values.size());
        assertEquals(String.valueOf(i), values.get(0));
      }
    }
  }
Пример #8
0
  public void send(GCMMessage messageBase) throws Exception {
    if (gcmURI == null) {
      throw new Exception("Error sending push. Google cloud messaging properties not provided.");
    }

    HttpPost httpPost = new HttpPost(gcmURI);
    httpPost.setHeader("Authorization", API_KEY);
    httpPost.setEntity(new StringEntity(messageBase.toJson(), ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      HttpEntity entity = response.getEntity();
      String responseMsg = EntityUtils.toString(entity);
      if (response.getStatusLine().getStatusCode() == 200) {
        GCMResponseMessage gcmResponseMessage = gcmResponseReader.readValue(responseMsg);
        if (gcmResponseMessage.failure == 1) {
          if (gcmResponseMessage.results != null && gcmResponseMessage.results.length > 0) {
            throw new Exception(
                "Error sending push. Problem : " + gcmResponseMessage.results[0].error);
          } else {
            throw new Exception("Error sending push. Token : " + messageBase.getToken());
          }
        }
      } else {
        EntityUtils.consume(entity);
        throw new Exception(responseMsg);
      }
    } finally {
      httpPost.releaseConnection();
    }
  }
  @Test
  public void serviceProviderCatalogsHaveValidAboutAttribute() throws XPathException, IOException {
    // Get all ServiceProviderCatalog elements and their rdf:about attributes, make sure that each
    // catalog has
    // an rdf:about attribute
    NodeList catalogAbouts =
        (NodeList)
            OSLCUtils.getXPath()
                .evaluate(
                    "//oslc_disc:ServiceProviderCatalog/@rdf:about", doc, XPathConstants.NODESET);
    NodeList catalogs =
        (NodeList)
            OSLCUtils.getXPath()
                .evaluate("//oslc_disc:ServiceProviderCatalog", doc, XPathConstants.NODESET);
    assertTrue(catalogAbouts.getLength() == catalogs.getLength());

    // Verify the rdf:about attribute links
    for (int i = 0; i < catalogAbouts.getLength(); i++) {
      String url = catalogAbouts.item(i).getNodeValue();
      assertFalse(url.isEmpty());
      HttpResponse response = OSLCUtils.getResponseFromUrl(baseUrl, url, basicCreds, "*/*");
      assertFalse(response.getStatusLine().getStatusCode() == 404);
      EntityUtils.consume(response.getEntity());
    }
  }
  /** Handle the httpResponse and return the SOAP XML String. */
  protected String handleResponse(final HttpResponse response, final HttpContext context)
      throws IOException {
    final HttpEntity entity = response.getEntity();
    if (null == entity.getContentType()
        || !entity.getContentType().getValue().startsWith("application/soap+xml")) {
      throw new WinRMRuntimeIOException(
          "Error when sending request to "
              + getTargetURL()
              + "; Unexpected content-type: "
              + entity.getContentType());
    }

    final InputStream is = entity.getContent();
    final Writer writer = new StringWriter();
    final Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    try {
      int n;
      final char[] buffer = new char[1024];
      while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
      }
    } finally {
      Closeables.closeQuietly(reader);
      Closeables.closeQuietly(is);
      EntityUtils.consume(response.getEntity());
    }

    return writer.toString();
  }
Пример #11
0
  /**
   * Send an HTTP message to a worker, producing helpful logging if there was a problem
   *
   * @param uriRequest The request to make
   * @param expectedStatus The expected return status
   * @return true if the method was successfully delivered & the worker gave the expected response
   */
  private boolean tellWorker(HttpUriRequest uriRequest, Response.Status expectedStatus) {
    try {
      HttpResponse response = httpClient.execute(uriRequest);

      if (response.getStatusLine().getStatusCode() != expectedStatus.getStatusCode()) {
        StatusLine statusLine = response.getStatusLine();
        EntityUtils.consume(response.getEntity());
        logger.warn(
            "Problem telling worker <"
                + metadata.getWorkerId()
                + "> "
                + "("
                + uriRequest.getURI()
                + "), "
                + "reason ["
                + statusLine.getStatusCode()
                + ": "
                + statusLine.getReasonPhrase()
                + "]");
        return false;
      }

      return true;
    } catch (IOException e) {
      logger.warn("Unable to communicated with worker " + metadata.toString());
      return false;
    }
  }
Пример #12
0
 public void login() throws IOException {
   String checkUrl = "http://web.im.baidu.com/check?callback=_nbc_.f1&v=30&time=" + guid;
   HttpGet getCheck = new HttpGet(checkUrl);
   HttpResponse res1 = httpClient.execute(getCheck);
   System.out.println("Check result: " + EntityUtils.toString(res1.getEntity()));
   EntityUtils.consume(res1.getEntity());
 }
  /**
   * Fetches user's e-mail - only public for testing.
   *
   * @param allToks OAuth tokens.
   * @param httpClient The HTTP client.
   */
  public int fetchEmail(final Map<String, String> allToks, final HttpClient httpClient) {
    final String endpoint = "https://www.googleapis.com/oauth2/v1/userinfo";
    final String accessToken = allToks.get("access_token");
    final HttpGet get = new HttpGet(endpoint);
    get.setHeader(HttpHeaders.Names.AUTHORIZATION, "Bearer " + accessToken);

    try {
      log.debug("About to execute get!");
      final HttpResponse response = httpClient.execute(get);
      final StatusLine line = response.getStatusLine();
      log.debug("Got response status: {}", line);
      final HttpEntity entity = response.getEntity();
      final String body = IOUtils.toString(entity.getContent(), "UTF-8");
      EntityUtils.consume(entity);
      log.debug("GOT RESPONSE BODY FOR EMAIL:\n" + body);

      final int code = line.getStatusCode();
      if (code < 200 || code > 299) {
        log.error("OAuth error?\n" + line);
        return code;
      }

      final Profile profile = JsonUtils.OBJECT_MAPPER.readValue(body, Profile.class);
      this.model.setProfile(profile);
      Events.sync(SyncPath.PROFILE, profile);
      // final String email = profile.getEmail();
      // this.model.getSettings().setEmail(email);
      return code;
    } catch (final IOException e) {
      log.warn("Could not connect to Google?", e);
    } finally {
      get.reset();
    }
    return -1;
  }
Пример #14
0
  public static boolean uploadFile(
      String url, String uploadKey, File file, Map<String, String> params) {
    // TODO httpClient连接关闭问题需要考虑
    try {
      HttpPost httppost = new HttpPost("http://www.new_magic.com/service.php");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart(uploadKey, new FileBody(file));
      for (Map.Entry<String, String> entry : params.entrySet()) {
        StringBody value = new StringBody(entry.getValue());
        reqEntity.addPart(entry.getKey(), value);
      }

      httppost.setEntity(reqEntity);
      HttpResponse response = httpClient.execute(httppost);
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == HttpStatus.SC_OK) {
        HttpEntity resEntity = response.getEntity();
        String body = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);

        Map<String, Object> responseMap = JsonUtil.parseJson(body, Map.class);
        if (responseMap.containsKey("code") && responseMap.get("code").equals(10000)) {
          return true;
        }
      }
    } catch (Exception e) {
      log.error("", e);
    }
    return false;
  }
Пример #15
0
  static void testBasicAuth() throws ClientProtocolException, IOException {
    HttpHost targetHost = new HttpHost("localhost", 8080, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("newuser", "tomcat"));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/simpleweb/protected");
    System.out.println(httpget.getURI());

    HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);

    HttpEntity entity = response.getEntity();

    System.out.println(response.getStatusLine().getStatusCode());
    String charset = HttpclientTutorial.getResponseCharset(response);
    HttpclientTutorial.output(entity, charset);

    EntityUtils.consume(entity);
  }
  public void success(HttpResponse response, String encoding) {
    String resultString = "";
    try {
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        final InputStream inputStream = entity.getContent();
        try {
          final StringBuilder sb = new StringBuilder();
          final char[] tmp = new char[1024];
          final Reader reader = new InputStreamReader(inputStream, encoding);
          int l;
          while ((l = reader.read(tmp)) != -1) {
            sb.append(tmp, 0, l);
          }
          resultString = sb.toString();
        } finally {
          inputStream.close();
          EntityUtils.consume(entity);
        }
      }
    } catch (ParseException | IOException e) {
    }

    Object object = null;
    try {
      object = this.gson.fromJson(resultString, type);
    } catch (JsonSyntaxException ex) {
      this.listener.failure(ex);
      throw ex;
    }
    if (listener != null) {
      listener.success(object);
    }
  }
Пример #17
0
  /**
   * Send an HTTP message to a worker and get the result
   *
   * <p>Note: expects the worker to respond with OK (200) status code.
   *
   * @param uriRequest The request to make
   * @return An InputStream of the response content
   */
  private InputStream askWorker(HttpUriRequest uriRequest) {
    try {
      HttpResponse response = httpClient.execute(uriRequest);

      if (response.getStatusLine().getStatusCode() != Response.Status.OK.getStatusCode()) {
        StatusLine statusLine = response.getStatusLine();
        EntityUtils.consume(response.getEntity());
        logger.warn(
            "Problem asking worker <"
                + metadata.getWorkerId()
                + "> "
                + "("
                + uriRequest.getURI()
                + "), "
                + "reason ["
                + statusLine.getStatusCode()
                + ": "
                + statusLine.getReasonPhrase()
                + "]");
      }

      return response.getEntity().getContent();
    } catch (IOException e) {
      logger.warn("Unable to communicated with worker " + metadata.toString());
      throw Throwables.propagate(e);
    }
  }
  public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {
      HttpGet httpget = new HttpGet("https://localhost/protected");

      System.out.println("executing request" + httpget.getRequestLine());
      CloseableHttpResponse response = httpclient.execute(httpget);
      try {
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
          System.out.println("Response content length: " + entity.getContentLength());
        }
        EntityUtils.consume(entity);
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
 @Override
 public String getChannels(String serverUrl, boolean premium)
     throws ClientProtocolException, UnsupportedEncodingException, IOException {
   String playLIst = null;
   CloseableHttpClient httpClient = HttpClientBuilder.create().build();
   // CloseableHttpClient httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build();
   HttpResponse login = httpClient.execute(getVideoStarLogin());
   EntityUtils.consume(login.getEntity());
   if (login.getStatusLine().getStatusCode() == 302) {
     HttpResponse getChannel = httpClient.execute(getChannelsRequest(login));
     if (getChannel.getStatusLine().getStatusCode() == 200) {
       VideoStarChannelRequest channels =
           jsonService.parseVideoStarChannels(EntityUtils.toString(getChannel.getEntity()));
       if (channels != null && channels.getStatus().equals("ok")) {
         return prepareChannelList(channels, serverUrl, premium);
         // return channelsString;
       } else if (channels != null && channels.getStatus().equals("error")) {
         // TODO
       } else {
         // TODO
       }
     }
   }
   return playLIst;
 }
  @Test
  public void testGetUserInvalid() throws Exception {
    IRODSAccount irodsAccount =
        testingPropertiesHelper.buildIRODSAccountFromTestProperties(testingProperties);

    StringBuilder sb = new StringBuilder();
    sb.append("http://localhost:");
    sb.append(
        testingPropertiesHelper.getPropertyValueAsInt(
            testingProperties, RestTestingProperties.REST_PORT_PROPERTY));
    sb.append("/user/iamaninvaliduser");

    DefaultHttpClientAndContext clientAndContext =
        RestAuthUtils.httpClientSetup(irodsAccount, testingProperties);
    try {

      HttpGet httpget = new HttpGet(sb.toString());
      httpget.addHeader("accept", "application/xml");

      HttpResponse response =
          clientAndContext.getHttpClient().execute(httpget, clientAndContext.getHttpContext());
      HttpEntity entity = response.getEntity();
      Assert.assertEquals(500, response.getStatusLine().getStatusCode());
      EntityUtils.consume(entity);

    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      clientAndContext.getHttpClient().getConnectionManager().shutdown();
    }
  }
Пример #21
0
  static void testProtectedResource() throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget, localContext);

    AuthState proxyAuthState =
        (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);

    System.out.println("Proxy auth scope: " + proxyAuthState.getAuthScope());
    System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme());
    System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials());

    AuthState targetAuthState =
        (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
    System.out.println("Target auth scope: " + targetAuthState.getAuthScope());
    System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme());
    System.out.println("Target auth credentials: " + targetAuthState.getCredentials());

    HttpEntity entity = response.getEntity();
    String charset = HttpclientTutorial.getResponseCharset(response);
    System.out.println("charset:" + charset);
    HttpclientTutorial.output(entity, charset);

    EntityUtils.consume(entity);
  }
  @Test
  public void testPreemptiveAuthenticationFailure() throws Exception {
    CountingAuthHandler requestHandler = new CountingAuthHandler();
    this.localServer.register("*", requestHandler);
    this.localServer.start();

    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("test", "stuff"));

    this.httpclient.setCredentialsProvider(credsProvider);

    HttpHost targethost = getServerHttp();

    HttpContext context = new BasicHttpContext();
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targethost, new BasicScheme());
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    HttpResponse response1 = this.httpclient.execute(targethost, httpget, context);
    HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    Assert.assertEquals(1, requestHandler.getCount());
  }
Пример #23
0
  public void pick() throws IOException {
    while (true) {
      pickUrl =
          String.format(
              "http://web.im.baidu.com/pick?v=30&session=&source=22&type=23&flag=1&seq=%d&ack=%s&guid=%s",
              sequence, ack, guid);

      HttpGet getRequest = new HttpGet(pickUrl);
      HttpResponse pickRes = httpClient.execute(getRequest);
      String entityStr = EntityUtils.toString(pickRes.getEntity());
      System.out.println("Pick result:" + entityStr);
      EntityUtils.consume(pickRes.getEntity());

      JSONObject jsonObject = JSONObject.fromObject(entityStr);
      JSONObject content = jsonObject.getJSONObject("content");
      if (content != null && content.get("ack") != null) {
        ack = (String) content.get("ack");
        JSONArray fields = content.getJSONArray("fields");
        JSONObject o = fields.getJSONObject(0);
        String fromUser = (String) o.get("from");
        System.out.println("++++Message from: " + fromUser);
      }
      updateSequence();

      if (sequence > 4) {
        break;
      }
    }
  }
  @Test
  public void testConnectionCloseAfterAuthenticationSuccess() throws Exception {
    this.localServer.register("*", new ClosingAuthHandler());
    this.localServer.start();

    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("test", "test"));

    TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy();

    this.httpclient.setCredentialsProvider(credsProvider);
    this.httpclient.setTargetAuthenticationStrategy(authStrategy);

    HttpContext context = new BasicHttpContext();

    HttpHost targethost = getServerHttp();

    for (int i = 0; i < 2; i++) {
      HttpGet httpget = new HttpGet("/");

      HttpResponse response = this.httpclient.execute(targethost, httpget, context);
      EntityUtils.consume(response.getEntity());
      Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    }
  }
Пример #25
0
  // 底层请求打印页面
  private byte[] sendRequest(HttpRequestBase request) throws Exception {
    CloseableHttpResponse response = httpclient.execute(request);

    // 设置超时
    setTimeOut(request, 5000);

    // 获取返回的状态列表
    StatusLine statusLine = response.getStatusLine();
    System.out.println("StatusLine : " + statusLine);

    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
      try {
        // 获取response entity
        HttpEntity entity = response.getEntity();
        System.out.println("getContentType : " + entity.getContentType().getValue());
        System.out.println("getContentEncoding : " + entity.getContentEncoding().getValue());

        // 读取响应内容
        byte[] responseBody = EntityUtils.toByteArray(entity);

        // 关闭响应流
        EntityUtils.consume(entity);
        return responseBody;
      } finally {
        response.close();
      }
    }
    return null;
  }
Пример #26
0
 private static void httpExecuteByStream(
     HttpClient httpClient, HttpUriRequest request, Response resp) throws Exception {
   HttpEntity entity = null;
   HttpResponse response;
   try {
     response = httpClient.execute(request);
     entity = response.getEntity();
     InputStream is = entity.getContent();
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     byte[] buffer = new byte[1024 * 1024];
     int read = -1;
     while ((read = is.read(buffer)) != -1) {
       bos.write(buffer, 0, read);
     }
     resp.code = response.getStatusLine().getStatusCode();
     resp.data = bos.toByteArray();
   } finally {
     if (entity != null) {
       try {
         EntityUtils.consume(entity);
       } catch (IOException e) {
       }
     }
   }
 }
  private Map<String, String> loadAllToks(final String code, int port, final HttpClient httpClient)
      throws IOException {
    final HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
    try {
      final List<? extends NameValuePair> nvps =
          Arrays.asList(
              new BasicNameValuePair("code", code),
              new BasicNameValuePair("client_id", model.getSettings().getClientID()),
              new BasicNameValuePair("client_secret", model.getSettings().getClientSecret()),
              new BasicNameValuePair("redirect_uri", OauthUtils.getRedirectUrl(port)),
              new BasicNameValuePair("grant_type", "authorization_code"));
      final HttpEntity entity = new UrlEncodedFormEntity(nvps, LanternConstants.UTF8);
      post.setEntity(entity);

      log.debug("About to execute post!");
      final HttpResponse response = httpClient.execute(post);

      log.debug("Got response status: {}", response.getStatusLine());
      final HttpEntity responseEntity = response.getEntity();
      final String body = IOUtils.toString(responseEntity.getContent());
      EntityUtils.consume(responseEntity);

      final Map<String, String> oauthToks = JsonUtils.OBJECT_MAPPER.readValue(body, Map.class);
      log.debug("Got oath data: {}", oauthToks);
      return oauthToks;
    } finally {
      post.reset();
    }
  }
Пример #28
0
  public LocalDocument getDocument(LocalQuery query, boolean recurring) throws IOException {
    HttpResponse response;
    if (recurring) {
      response = core.post(getRecurringUrl, query.toJson());
    } else {
      response = core.post(getUrl, query.toJson());
    }

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      LocalDocument ld;
      try {
        ld = new LocalDocument(EntityUtils.toString(response.getEntity()));
      } catch (JsonException e) {
        throw new IOException(e);
      }
      InternalLogger.debug("Received document with ID " + ld.getID());
      currentDocument = ld;
      return ld;
    } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
      InternalLogger.debug("No document found matching query");
      EntityUtils.consume(response.getEntity());
      return null;
    } else {
      logUnexpected(response);
      return null;
    }
  }
    private void retrieveMonitorDetails(final HttpResponse res) {
      Header[] headers = res.getHeaders(HttpHeader.LOCATION);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.location = URI.create(headers[0].getValue());
      } else {
        throw new AsyncRequestException(
            "Invalid async request response. Monitor URL '" + headers[0].getValue() + "'");
      }

      headers = res.getHeaders(HttpHeader.RETRY_AFTER);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.retryAfter = Integer.parseInt(headers[0].getValue());
      }

      headers = res.getHeaders(HttpHeader.PREFERENCE_APPLIED);
      if (ArrayUtils.isNotEmpty(headers)) {
        for (Header header : headers) {
          if (header.getValue().equalsIgnoreCase(new ODataPreferences().respondAsync())) {
            preferenceApplied = true;
          }
        }
      }
      try {
        EntityUtils.consume(res.getEntity());
      } catch (IOException ex) {
        Logger.getLogger(AsyncRequestWrapperImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
Пример #30
0
  public void run() {
    for (Object MSISDN : mListMSISDN) {
      String TextResponse = "";

      String XMLReqeust = String.format(Template, MSISDN);

      HttpPost mPost = new HttpPost(URL);

      StringEntity mEntity = new StringEntity(XMLReqeust, ContentType.create("text/xml", "UTF-8"));

      mPost.setEntity(mEntity);
      HttpClient mClient = new DefaultHttpClient();
      try {
        HttpResponse response = mClient.execute(mPost);

        HttpEntity entity = response.getEntity();
        TextResponse = EntityUtils.toString(entity);

        System.out.println(TextResponse);

        EntityUtils.consume(entity);
      } catch (Exception ex) {
        mLog.log.error(ex);
      } finally {
        mLog.log.debug("REQUEST --> " + XMLReqeust);
        mLog.log.debug("RESPONSE --> " + TextResponse);
      }
    }
    mLog.log.debug("KET THUC THEAD " + ThreadIndex);
  }