Beispiel #1
1
  private HttpClient getClient() {
    if (client == null) {
      HttpClientBuilder clientBuilder = HttpClients.custom();
      RequestConfig.Builder configBuilder = RequestConfig.custom();
      if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        isUsingProxy = true;
        InetSocketAddress adr = (InetSocketAddress) proxy.address();
        clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
      }
      if (timeout != null) {
        configBuilder.setConnectTimeout(timeout.intValue());
      }
      if (readTimeout != null) {
        configBuilder.setSocketTimeout(readTimeout.intValue());
      }
      if (followRedirects != null) {
        configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
      }
      if (hostnameverifier != null) {
        SSLConnectionSocketFactory sslConnectionFactory =
            new SSLConnectionSocketFactory(getSSLContext(), hostnameverifier);
        clientBuilder.setSSLSocketFactory(sslConnectionFactory);
        Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .build();
        clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
      }
      clientBuilder.setDefaultRequestConfig(configBuilder.build());
      client = clientBuilder.build();
    }

    return client;
  }
Beispiel #2
0
  public String unTag(NewTagModel untag) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + untag.get_id());
      oldTagGet.addHeader(authHeaderKey, authHeaderValue);
      oldTagGet.addHeader(acceptHeaderKey, acceptHeaderValue);
      oldTagGet.addHeader(contentHeaderKey, contentHeaderValue);
      HttpResponse oldTagResp = httpclient.execute(oldTagGet);
      Gson gson = new Gson();
      TagModel updatedtag =
          gson.fromJson(EntityUtils.toString(oldTagResp.getEntity()), TagModel.class);
      httpclient.close();

      updatedtag.getTagged().remove(untag.getUsername());
      LOGGER.info(untag.get_id() + " is untagging " + untag.getUsername());
      HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + untag.get_id());
      updatedTagPut.addHeader(authHeaderKey, authHeaderValue);
      updatedTagPut.addHeader(acceptHeaderKey, acceptHeaderValue);
      updatedTagPut.addHeader(contentHeaderKey, contentHeaderValue);
      updatedTagPut.setEntity(new StringEntity(gson.toJson(updatedtag)));
      httpclient = HttpClients.createDefault();
      HttpResponse updatedTagResp = httpclient.execute(updatedTagPut);
      if (!(updatedTagResp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)) {
        String updatedTagEntity = EntityUtils.toString(updatedTagResp.getEntity());
        httpclient.close();
        return updatedTagEntity;
      }
      httpclient.close();
      return successJson;
    } catch (Exception e) {
      e.printStackTrace();
      return failJson;
    }
  }
Beispiel #3
0
 public static CloseableHttpClient createSSLClientDefault() {
   try {
     SSLContext sslContext =
         new SSLContextBuilder()
             .loadTrustMaterial(
                 null,
                 new TrustStrategy() {
                   // 信任所有
                   public boolean isTrusted(X509Certificate[] chain, String authType)
                       throws CertificateException {
                     return true;
                   }
                 })
             .build();
     SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
     return HttpClients.custom().setSSLSocketFactory(sslsf).build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return HttpClients.createDefault();
 }
  @Test
  public void testDownloadFileBy() throws Exception {
    randomPrivateBucket = B2TestHelper.createRandomPrivateBucket();
    b2FileResponse = B2TestHelper.uploadTemporaryFileToBucket(randomPrivateBucket.getBucketId());

    B2DownloadFileResponse b2DownloadFileResponse =
        new B2DownloadFileByNameRequest(
                HttpClients.createDefault(),
                B2TestHelper.getB2AuthorizeAccountResponse(),
                randomPrivateBucket.getBucketName(),
                b2FileResponse.getFileName())
            .getResponse();
    assertEquals(
        B2TestHelper.DUMMY_FILE_CONTENT,
        IOUtils.toString(b2DownloadFileResponse.getContent(), Charset.defaultCharset()));

    b2DownloadFileResponse =
        new B2DownloadFileByIdRequest(
                HttpClients.createDefault(),
                B2TestHelper.getB2AuthorizeAccountResponse(),
                b2FileResponse.getFileId())
            .getResponse();
    assertEquals(
        B2TestHelper.DUMMY_FILE_CONTENT,
        IOUtils.toString(b2DownloadFileResponse.getContent(), Charset.defaultCharset()));

    B2TestHelper.deleteFile(b2FileResponse.getFileName(), b2FileResponse.getFileId());
    B2TestHelper.deleteBucket(randomPrivateBucket.getBucketId());
  }
Beispiel #5
0
  public String updateTagged(NewTagModel newtag) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      // get old tagged from cloudant
      // in NewTagModel - get_id() returns person initiating tag - getUsername() returns person to
      // tag
      HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + newtag.get_id());
      oldTagGet.addHeader(authHeaderKey, authHeaderValue);
      oldTagGet.addHeader(acceptHeaderKey, acceptHeaderValue);
      oldTagGet.addHeader(contentHeaderKey, contentHeaderValue);
      HttpResponse oldTagResp = httpclient.execute(oldTagGet);
      Gson gson = new Gson();
      TagModel updatedtag =
          gson.fromJson(EntityUtils.toString(oldTagResp.getEntity()), TagModel.class);
      httpclient.close();

      // check for and don't allow retagging - currently front-end design shouldn't allow for this
      // but needs to be checked on server side as well
      if (updatedtag.getTagged().contains(newtag.getUsername())) {
        LOGGER.info(
            newtag.getUsername() + " already exists in tagged list for " + updatedtag.get_id());
        return alreadyTaggedJson;
      }

      // update array of tagged in updatedtag and update entry in cloudant
      updatedtag.getTagged().add(newtag.getUsername());
      HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + newtag.get_id());
      updatedTagPut.addHeader(authHeaderKey, authHeaderValue);
      updatedTagPut.addHeader(acceptHeaderKey, acceptHeaderValue);
      updatedTagPut.addHeader(contentHeaderKey, contentHeaderValue);
      updatedTagPut.setEntity(new StringEntity(gson.toJson(updatedtag)));
      httpclient = HttpClients.createDefault();
      HttpResponse updatedTagResp = httpclient.execute(updatedTagPut);
      if (!(updatedTagResp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)) {
        String updatedTagEntity = EntityUtils.toString(updatedTagResp.getEntity());
        httpclient.close();
        return updatedTagEntity;
      }
      httpclient.close();
      LOGGER.info(newtag.get_id() + " tagged " + newtag.getUsername());
      return successJson;
    } catch (Exception e) {
      try {
        httpclient.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();
      return failJson;
    }
  }
 /**
  * Return a http client instance
  *
  * @param protocol- service endpoint protocol http/https
  * @return
  */
 public static HttpClient getHttpClient(int port, String protocol)
     throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
   HttpClient httpclient;
   if (HTTPS_PROTOCOL.equals(protocol)) {
     SSLContextBuilder builder = new SSLContextBuilder();
     builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
     SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
     httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
   } else {
     httpclient = HttpClients.createDefault();
   }
   return httpclient;
 }
Beispiel #7
0
 static {
   HttpClientBuilder custom = HttpClients.custom();
   custom.setUserAgent("Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0");
   RequestConfig config =
       RequestConfig.custom()
           .setConnectionRequestTimeout(5 * 1000)
           .setSocketTimeout(30 * 1000)
           .setConnectTimeout(5 * 1000)
           .build();
   custom.setDefaultRequestConfig(config);
   httpclient = custom.build();
   minHttpclient = HttpClients.createMinimal();
 }
  @Test
  public void testDownloadByFilePath() throws Exception {
    randomPrivateBucket = B2TestHelper.createRandomPrivateBucket();
    B2GetUploadUrlResponse b2GetUploadUrlResponse =
        B2TestHelper.getUploadUrl(randomPrivateBucket.getBucketId());
    File file = File.createTempFile("backblaze-api-test", ".txt");
    FileWriter fileWriter = new FileWriter(file);
    fileWriter.write("hello world!");
    fileWriter.flush();
    fileWriter.close();

    String testFileName = "some/file/path/" + file.getName();
    B2FileResponse b2UploadFileResponse =
        new B2UploadFileRequest(
                HttpClients.createDefault(),
                B2TestHelper.getB2AuthorizeAccountResponse(),
                b2GetUploadUrlResponse,
                testFileName,
                file,
                ChecksumHelper.calculateSha1(file))
            .getResponse();

    String fileName = b2UploadFileResponse.getFileName();
    String fileId = b2UploadFileResponse.getFileId();

    B2DownloadFileResponse b2DownloadFileResponse =
        new B2DownloadFileByNameRequest(
                HttpClients.createDefault(),
                B2TestHelper.getB2AuthorizeAccountResponse(),
                randomPrivateBucket.getBucketName(),
                testFileName)
            .getResponse();
    assertEquals(fileName, b2DownloadFileResponse.getFileName());
    // now we need to delete the file as well to clean up after ourselves

    B2DeleteFileVersionResponse b2DeleteFileVersionResponse =
        new B2DeleteFileVersionRequest(
                HttpClients.createDefault(),
                B2TestHelper.getB2AuthorizeAccountResponse(),
                testFileName,
                fileId)
            .getResponse();

    assertEquals(fileName, b2DeleteFileVersionResponse.getFileName());
    assertEquals(fileId, b2DeleteFileVersionResponse.getFileId());

    B2TestHelper.deleteBucket(randomPrivateBucket.getBucketId());
  }
Beispiel #9
0
 /**
  * 代理方式
  *
  * @param proxy
  */
 public HTCtest(HttpProxy proxy) {
   if (proxy != null) {
     httpclient = getHttpClientWithProxy(proxy);
   } else {
     httpclient = HttpClients.createDefault();
   }
 }
Beispiel #10
0
  public static Object fetch(DocumentSource source) {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      URIBuilder builder = new URIBuilder(source.url);
      for (Entry<String, String> it : source.parameters.entrySet()) {
        builder.addParameter(it.getKey(), it.getValue());
      }
      URI uri = builder.build();

      HttpUriRequest request = new HttpGet(uri);
      request.addHeader("Accept", "application/json");
      CloseableHttpResponse response = httpclient.execute(request);

      String headers = response.getFirstHeader("Content-Type").getValue();
      InputStream inputStream = response.getEntity().getContent();
      if (headers.contains("text/html")) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        Document document = Jsoup.parse(inputStream, null, source.url);
        return document;
      } else if (headers.contains("json")) {
        ObjectMapper om = new ObjectMapper();
        return om.readValue(inputStream, HashMap.class);
      } else {
        IOUtils.copy(inputStream, System.err);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return null;
  }
Beispiel #11
0
  public static String shortIt(String longUrl) {
    if (!longUrl.startsWith("http")) {
      longUrl = "http://" + longUrl;
    }
    CloseableHttpClient httpclient = HttpClients.custom().build(); // 可以帮助记录cookie
    String result = longUrl;
    String uri = "http://vwz.me/API.php?url=" + longUrl + "&callback=json";
    HttpGet get = new HttpGet(uri);
    try {
      CloseableHttpResponse execute = httpclient.execute(get);
      int statusCode = execute.getStatusLine().getStatusCode();
      switch (statusCode) {
        case 200:
          String html = IOUtils.toString(execute.getEntity().getContent(), "UTF-8");
          String json = html.substring(5, html.length() - 2);
          logger.info("json : {}", json);
          result = parseMsg(json);
          break;
        default:
          break;
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      httpclient.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    logger.info("short {} to {}", longUrl, result);
    return result;
  }
Beispiel #12
0
 private static HttpClient getHttpClientByUrl(String url) {
   if (isHttps(url)) {
     return getHttpsClient();
   } else {
     return HttpClients.createDefault();
   }
 }
  protected String getRequest() throws Exception {
    String ret = "";

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(coreJobServerUrl + "/hoot-services/ingest/customscript/getlist");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {

      if (response.getStatusLine().getStatusCode() != 200) {
        String reason = response.getStatusLine().getReasonPhrase();
        if (reason == null) {
          reason = "Unkown reason.";
        }
        throw new Exception(reason);
      }

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        long len = entity.getContentLength();
        ret = EntityUtils.toString(entity);
      }
    } finally {
      response.close();
    }

    return ret;
  }
Beispiel #14
0
  /**
   * @param uri
   * @return
   */
  public static String getResponseBody(String uri) {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {
      HttpGet httpGet = new HttpGet(uri);
      CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

      try {
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity);
      } finally {
        if (httpResponse != null) {
          httpResponse.close();
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (httpClient != null) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return null;
  }
  /**
   * Uploads a {@code File} with PRIVATE read access.
   *
   * @param uri upload {@link URI}
   * @param contentTypeString content type
   * @param contentFile the file to upload
   * @throws IOException
   */
  public static void uploadPrivateContent(
      final URI uri, final String contentTypeString, final File contentFile) throws IOException {

    LOGGER.info(
        "uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
      throw new IOException(
          String.format(
              "An error occurred while trying to upload private file - %d: %s",
              statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info(
        "uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});
  }
Beispiel #16
0
 HttpRequestBuilder httpClient() {
   InetSocketAddress[] addresses = cluster().httpAddresses();
   InetSocketAddress address = addresses[randomInt(addresses.length - 1)];
   return new HttpRequestBuilder(HttpClients.createDefault())
       .host(address.getHostName())
       .port(address.getPort());
 }
  String getSentiment(String text) throws ClientProtocolException, IOException {
    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost =
        new HttpPost("http://access.alchemyapi.com/calls/text/TextGetTextSentiment");
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    String apiKey = APIKey;

    params.add(new BasicNameValuePair("apikey", apiKey));
    params.add(new BasicNameValuePair("text", text));
    params.add(new BasicNameValuePair("outputMode", "json"));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    String ret = null;
    if (entity != null) {
      InputStream instream = entity.getContent();
      try {
        ret = EntityUtils.toString(entity);
      } finally {
        instream.close();
      }
    }
    return ret;
  }
 private HttpClient createHttpClient() {
   if (Boolean.parseBoolean(System.getProperty("proxySet"))) {
     HttpHost httpHost =
         new HttpHost(
             System.getProperty("http.proxyHost"),
             Integer.parseInt(System.getProperty("http.proxyPort")));
     DefaultProxyRoutePlanner defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(httpHost);
     return HttpClients.custom().setRoutePlanner(defaultProxyRoutePlanner).build();
     //            todo - need to support SOCKS protocol for this solution to work - jamesdbloom
     // 12/01/2014
     //            return HttpClients.custom().setRoutePlanner(new
     // SystemDefaultRoutePlanner(ProxySelector.getDefault())).build();
   } else {
     return HttpClients.custom().build();
   }
 }
  /**
   * Tests that if a socket fails to connect, the allocated connection is properly released back to
   * the connection manager.
   */
  @Test
  public void testSocketConnectFailureReleasesConnection() throws Exception {
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final ConnectionRequest connrequest = Mockito.mock(ConnectionRequest.class);
    Mockito.when(connrequest.get(Mockito.anyInt(), Mockito.any(TimeUnit.class))).thenReturn(conn);
    final HttpClientConnectionManager connmgr = Mockito.mock(HttpClientConnectionManager.class);
    Mockito.doThrow(new ConnectException())
        .when(connmgr)
        .connect(
            Mockito.any(HttpClientConnection.class),
            Mockito.any(HttpRoute.class),
            Mockito.anyInt(),
            Mockito.any(HttpContext.class));

    Mockito.when(connmgr.requestConnection(Mockito.any(HttpRoute.class), Mockito.any()))
        .thenReturn(connrequest);

    final HttpClient client = HttpClients.custom().setConnectionManager(connmgr).build();
    final HttpContext context = new BasicHttpContext();
    final HttpGet httpget = new HttpGet("http://www.example.com/a");

    try {
      client.execute(httpget, context);
      Assert.fail("expected IOException");
    } catch (final IOException expected) {
    }

    Mockito.verify(connmgr).releaseConnection(conn, null, 0, TimeUnit.MILLISECONDS);
  }
  public static void downloadPageByGetMethod(String url, String[] arg) throws IOException {

    // 1、�?过HttpGet获取到response对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 注意,必�?��加上http://的前�?��否则会报:Target host is null异常�?
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response = httpClient.execute(httpGet);

    InputStream is = null;
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      try {
        // 2、获取response的entity�?
        HttpEntity entity = response.getEntity();

        // 3、获取到InputStream对象,并对内容进行处�?
        is = entity.getContent();

        String fileName = getFileName(arg);

        saveToFile(saveUrl, fileName, is);
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } finally {

        if (is != null) {
          is.close();
        }
        if (response != null) {
          response.close();
        }
      }
    }
  }
Beispiel #21
0
  /**
   * * Recreates POST from web interface, sends it to yodaQA and gets response
   *
   * @param address Address of yodaQA
   * @param request POST from web interface containing question
   * @param concepts More concepts to send to yodaQA
   * @return response of yodaQA
   */
  public String getPOSTResponse(
      String address,
      Request request,
      String question,
      ArrayDeque<Concept> concepts,
      String artificialClue) {
    String result = "";
    try {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(address);
      PostRecreator postRecreator = new PostRecreator();
      httpPost = postRecreator.recreatePost(httpPost, request, question, concepts, artificialClue);

      CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

      BufferedReader reader =
          new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

      String inputLine;
      StringBuffer postResponse = new StringBuffer();

      while ((inputLine = reader.readLine()) != null) {
        postResponse.append(inputLine);
      }
      reader.close();
      httpClient.close();
      result = postResponse.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
Beispiel #22
0
 public HttpBuildCache(URI root) {
   if (!root.getPath().endsWith("/")) {
     throw new IncompleteArgumentException("HTTP cache root URI must end with '/'");
   }
   this.root = root;
   this.httpClient = HttpClients.createDefault();
 }
  public static String sendGET(final String url)
      throws ClientProtocolException, IOException, HttpRequestFailureException {
    LOGGER.infof("Entering sendGET(%s)", url);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    // httpGet.addHeader("User-Agent", USER_AGENT);
    CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
    final int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode != 200) {
      throw new HttpRequestFailureException(statusCode);
    }
    BufferedReader reader =
        new BufferedReader(
            new InputStreamReader(httpResponse.getEntity().getContent(), STREAM_CHARSET));

    String inputLine;
    StringBuffer response = new StringBuffer();
    final String lineSeparator = System.getProperty("line.separator");
    while ((inputLine = reader.readLine()) != null) {
      response.append(inputLine);
      response.append(lineSeparator);
    }
    reader.close();
    httpClient.close();

    String result = response.toString();
    if (LOGGER.isTraceEnabled()) {
      LOGGER.tracef("Leaving sendGET(): %s", result);
    } else {
      LOGGER.info("Leaving sendGET()");
    }
    return result;
  }
  @Test
  public static void depositeDetailTest() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpPost post = new HttpPost("http://192.168.2.111:8578/service?channel=QueryNoticePage");
      List<NameValuePair> list = new ArrayList<NameValuePair>();
      list.add(new BasicNameValuePair("platformId", "82044"));
      list.add(new BasicNameValuePair("appKey", "1"));

      post.setEntity(new UrlEncodedFormEntity(list));
      CloseableHttpResponse response = httpclient.execute(post);

      try {
        System.out.println(response.getStatusLine());
        HttpEntity entity2 = response.getEntity();
        String entity = EntityUtils.toString(entity2);
        if (entity.contains("code\":\"0")) {
          System.out.println("Success!");
          System.out.println("response content:" + entity);
        } else {
          System.out.println("Failure!");
          System.out.println("response content:" + entity);
          AssertJUnit.fail(entity);
        }
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
  public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

      credentialsProvider.setCredentials(
          new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password));

      httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
      httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {
      if (_logger.isWarnEnabled()) {
        _logger.warn("Login and password are required");
      }
    }

    try {
      setProxyHost(httpClientBuilder);

      _closeableHttpClient = httpClientBuilder.build();

      if (_logger.isDebugEnabled()) {
        _logger.debug("Configured client for " + _protocol + "://" + _hostName);
      }
    } catch (Exception e) {
      _logger.error("Unable to configure client", e);
    }
  }
  @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";
  }
Beispiel #27
0
  /**
   * @param url
   * @param formData 提交的数
   * @throws IOException
   */
  public static void post(String url, Map<String, Object> formData) throws Exception {
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    if (formData != null) {
      Iterator<Map.Entry<String, Object>> iterator = formData.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        String key = next.getKey();
        Object value = next.getValue();
        formparams.add(new BasicNameValuePair(key, value.toString()));
      }
    }

    HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "utf-8");

    RequestConfig requestConfig =
        RequestConfig.custom()
            .setSocketTimeout(50000)
            .setConnectTimeout(50000)
            .setConnectionRequestTimeout(50000)
            .build();
    post.setEntity(reqEntity);
    post.setConfig(requestConfig);
    HttpResponse response = client.execute(post);
    if (response.getStatusLine().getStatusCode() != 200) {
      throw new Exception("请求失败");
    }
  }
  public final void run() {
    proccess();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost =
        new HttpPost(
            "https://api.telegram.org/bot115447632:AAGiH7bX_7dpywsXWONvsJPESQe-N7EmcQI/sendMessage");
    httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
    httpPost.addHeader("charset", "UTF-8");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("chat_id", String.valueOf(update.message.chat.id)));
    urlParameters.add(new BasicNameValuePair("text", mensagem));
    if (teclado != null) urlParameters.add(new BasicNameValuePair("reply_markup", teclado));
    if (mensagemRetornoID != null)
      urlParameters.add(
          new BasicNameValuePair("reply_to_message_id", mensagemRetornoID.toString()));

    try {
      httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
      httpclient.execute(httpPost);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @Test
  public void testTracingFalse()
      throws ClientProtocolException, IOException, UnsatisfiedExpectationException {
    when(clientTracer.startNewSpan(PATH)).thenReturn(null);

    final HttpRequestImpl request = new HttpRequestImpl();
    request
        .method(Method.GET)
        .path(PATH)
        .httpMessageHeader(BraveHttpHeaders.Sampled.getName(), "false");
    final HttpResponseImpl response = new HttpResponseImpl(200, null, null);
    responseProvider.set(request, response);

    final CloseableHttpClient httpclient =
        HttpClients.custom()
            .addInterceptorFirst(new BraveHttpRequestInterceptor(clientTracer))
            .addInterceptorFirst(new BraveHttpResponseInterceptor(clientTracer))
            .build();
    try {
      final HttpGet httpGet = new HttpGet(REQUEST);
      final CloseableHttpResponse httpClientResponse = httpclient.execute(httpGet);
      assertEquals(200, httpClientResponse.getStatusLine().getStatusCode());
      httpClientResponse.close();
      mockServer.verify();

      final InOrder inOrder = inOrder(clientTracer);
      inOrder.verify(clientTracer).startNewSpan(PATH);
      inOrder.verify(clientTracer).submitBinaryAnnotation("request", "GET " + PATH);
      inOrder.verify(clientTracer).setClientSent();
      inOrder.verify(clientTracer).setClientReceived();
      verifyNoMoreInteractions(clientTracer);
    } finally {
      httpclient.close();
    }
  }
  public static CloseableHttpClient buildHttpClient() throws Exception {

    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {}

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {}
          }
        };

    SSLContext sslcontext = SSLContext.getInstance("SSL");
    sslcontext.init(null, trustAllCerts, new java.security.SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(
            sslcontext,
            new String[] {"TLSv1"},
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    return httpclient;
  }