Exemplo n.º 1
0
 public static HttpHeaderInfo getHttpHeader(String url, Map<Object, Object> headers)
     throws ClientProtocolException, IOException {
   HttpGet httpGet = new HttpGet(url);
   if (headers != null) {
     for (Map.Entry<Object, Object> entry : headers.entrySet()) {
       httpGet.addHeader(entry.getKey() + "", entry.getValue() + "");
     }
   }
   CloseableHttpResponse response = minHttpclient.execute(httpGet);
   try {
     response.close();
     HttpHeaderInfo headerInfo = new HttpHeaderInfo();
     headerInfo.setStatus(response.getStatusLine().getStatusCode());
     headerInfo.setReasonPhrase(response.getStatusLine().getReasonPhrase());
     Header[] allHeaders = response.getAllHeaders();
     if (allHeaders != null) {
       Map<String, Object> headerMap = new HashMap<String, Object>();
       for (Header header : allHeaders) {
         headerMap.put(header.getName(), header.getValue());
       }
       headerInfo.setHeaders(headerMap);
     }
     return headerInfo;
   } finally {
     response.close();
   }
 }
Exemplo n.º 2
0
 public void getIPTShows() {
   CloseableHttpClient httpClient = HttpClientBuilder.create().build();
   CloseableHttpResponse response = null;
   String pageURL = "https://www.iptorrents.com";
   try {
     HttpGet httpGet = new HttpGet(pageURL);
     httpGet.addHeader(
         "User-Agent",
         "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36");
     response = httpClient.execute(httpGet);
     response.removeHeaders("Transfer-Encoding");
     HttpPost thePost = new HttpPost(pageURL + "?username=mcpchelper81&password=ru68ce48&php=");
     thePost.setHeaders(response.getAllHeaders());
     response.close();
     response = null;
     response = httpClient.execute(thePost);
     httpGet = new HttpGet("https://www.iptorrents.com/t?5");
     httpGet.setHeaders(response.getHeaders("set-cookie"));
     httpGet.addHeader(
         "accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
     httpGet.addHeader("accept-encoding", "gzip, deflate, sdch");
     httpGet.addHeader("accept-language", "en-US,en;q=0.8");
     httpGet.addHeader("dnt", "1");
     httpGet.addHeader("upgrade-insecure-requests", "1");
     httpGet.addHeader(
         "user-agent",
         "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
     response.close();
     response = null;
     response = httpClient.execute(httpGet);
     Header contentType = response.getFirstHeader("Content-Type");
     HttpEntity httpEntity = response.getEntity();
     String[] contentArray = contentType.getValue().split(";");
     String charset = "UTF-8";
     if (contentArray.length > 1 && contentArray[1].contains("=")) {
       charset = contentArray[1].trim().split("=")[1];
     }
     Document pageDoc = Jsoup.parse(httpEntity.getContent(), charset, httpGet.getURI().getPath());
     Elements results = pageDoc.getElementsByClass("torrents");
     response.close();
     Elements rawShowObjects = results.select("tr");
     IPTToTvShowEpisode makeShows = new IPTToTvShowEpisode();
     List<TvShowEpisode> theShows = makeShows.makeTSEBeans(rawShowObjects);
     DBActions.insertIPTTvEpisodes(theShows, "https://www.iptorrents.com/t?5");
   } catch (MalformedURLException MURLe) {
     MURLe.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /**
   * Gets the page contents from the URL and call HashMap insert method
   *
   * @param url
   * @throws Exception
   */
  private static void getPageText(String url) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    InputStreamReader istream = new InputStreamReader(entity.getContent(), "UTF-8");
    try {
      if (entity != null) {
        BufferedReader rd = new BufferedReader(istream);
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
          result.append(line);
        }

        // Using Jsoup to extract text from html
        Document doc = Jsoup.parse(result.toString());
        String str = doc.text().replaceAll("\\P{Alpha}-", " ").toLowerCase();
        String[] arr = str.split("[^a-z-]+");

        // Call method to insert into HashMap
        insertWords(arr);
      }
    } finally {
      response.close();
      httpclient.close();
      istream.close();
    }
  }
Exemplo n.º 4
0
  private boolean getDataFromSohuUrl(Stock stock) {
    boolean flg = true;
    CloseableHttpClient hpc = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String bUrl = assembleUrl(stock);
    String ss = null;
    try {

      HttpGet httpget = new HttpGet(bUrl);
      response = hpc.execute(httpget);
      HttpEntity he = response.getEntity();
      String s1 = EntityUtils.toString(he);
      List<String> li1 = new ArrayList<String>();
      this.handleData(s1, stock, li1);
      CommonDao cd = new CommonDao();
      cd.insertStockDateData2(stock, li1);
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(ss);
      flg = false;
    } finally {
      try {
        if (response != null) {
          response.close();
        }
        if (hpc != null) {
          hpc.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
        flg = false;
      }
    }
    return flg;
  }
  /**
   * Sends an HTTP request to the monitoring service to report performance measures of a bounce
   * proxy instance.
   *
   * @throws IOException
   */
  private void sendPerformanceReportAsHttpRequest() throws IOException {

    final String url = bounceProxyControllerUrl.buildReportPerformanceUrl();
    logger.debug("Using monitoring service URL: {}", url);

    Map<String, Integer> performanceMap = bounceProxyPerformanceMonitor.getAsKeyValuePairs();
    String serializedMessage = objectMapper.writeValueAsString(performanceMap);

    HttpPost postReportPerformance = new HttpPost(url.trim());
    // using http apache constants here because JOYNr constants are in
    // libjoynr which should not be included here
    postReportPerformance.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    postReportPerformance.setEntity(new StringEntity(serializedMessage, "UTF-8"));

    CloseableHttpResponse response = null;
    try {
      response = httpclient.execute(postReportPerformance);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();

      if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) {
        logger.error("Failed to send performance report: {}", response);
        throw new JoynrHttpException(statusCode, "Failed to send performance report.");
      }

    } finally {
      if (response != null) {
        response.close();
      }
    }
  }
Exemplo n.º 6
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;
  }
  public void run() {

    try {

      //			System.out.println(Thread.currentThread().getName() + ": " + System.currentTimeMillis() +
      // ": " + "Connecting");
      log.writeLog(Thread.currentThread().getName() + ": " + "Connecting");

      CloseableHttpResponse response = client.execute(get);

      //			System.out.println(Thread.currentThread().getName() + ": " + System.currentTimeMillis() +
      // ": " + response.getStatusLine().getStatusCode() + " " +
      // response.getStatusLine().getReasonPhrase());
      log.writeLog(
          Thread.currentThread().getName()
              + ": "
              + response.getStatusLine().getStatusCode()
              + " "
              + response.getStatusLine().getReasonPhrase());
      response.close();

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      //			System.out.println(Thread.currentThread().getName() + ": " + System.currentTimeMillis() +
      // ": " + "Connection timeout");
      identifier.updateMinMax(Integer.parseInt(Thread.currentThread().getName().split("-")[1]));
      log.writeLog(Thread.currentThread().getName() + ": " + "Connection timeout");
      //			e.printStackTrace();
    }
  }
Exemplo n.º 8
0
 public void download() {
   InputStream in = null;
   CloseableHttpResponse res = null;
   while (true) {
     try {
       Center center = p.next();
       File file = new File(path + "\\" + center.getX() + "_" + center.getY() + ".png");
       file.createNewFile();
       HttpGet get = new HttpGet(centerToURL(center));
       System.out.println(get.getURI().toString());
       res = client.execute(get);
       in = res.getEntity().getContent();
       BufferedImage image = ImageIO.read(in);
       WriteImage(image, file);
     } catch (Exception e) {
       e.printStackTrace();
       break;
     } finally {
       try {
         in.close();
         res.close();
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
     try {
       savePictureInfo();
     } catch (Exception 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();
    }
  }
Exemplo n.º 10
0
 public String connectByPost(String url) {
   HttpPost httpPost = new HttpPost(url);
   System.out.println(url);
   try {
     // httpPost.addHeader("Referer",
     // "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131202001");
     List<Cookie> cookies = cookieStore.getCookies();
     for (Cookie cookie : cookies) {
       if (cookie.getName().equals("ptwebqq")) {
         this.ptWebqq = cookie.getValue();
       }
     }
     System.out.println(ptWebqq);
     httpPost.addHeader("clientid", "48847830");
     httpPost.addHeader("psessionid", "null");
     httpPost.addHeader(
         "r",
         "{\"status\":\"online\",\"ptwebqq\":\""
             + this.ptWebqq
             + "\",\"passwd_sig\":\"\",\"clientid\":\"48847830\",\"psessionid\":null}");
     CloseableHttpResponse response = this.httpClient.execute(httpPost);
     HttpEntity entity = response.getEntity();
     this.getContent = EntityUtils.toString(entity);
     response.close();
     httpPost.abort();
   } catch (Exception e) {
     // TODO 自动生成的 catch 块
     e.printStackTrace();
   } finally {
     return getContent;
   }
 }
Exemplo n.º 11
0
 public void getTPBShows() {
   CloseableHttpClient httpClient = HttpClientBuilder.create().build();
   CloseableHttpResponse response = null;
   try {
     HttpGet httpGet = new HttpGet(pageURL);
     httpGet.addHeader(
         "User-Agent",
         "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36");
     response = httpClient.execute(httpGet);
     HttpEntity httpEntity = response.getEntity();
     Header contentType = response.getFirstHeader("Content-Type");
     String[] contentArray = contentType.getValue().split(";");
     String charset = "UTF-8";
     // String mimeType = contentArray[0].trim();
     if (contentArray.length > 1 && contentArray[1].contains("=")) {
       charset = contentArray[1].trim().split("=")[1];
     }
     Document pageDoc = Jsoup.parse(httpEntity.getContent(), charset, httpGet.getURI().getPath());
     Element results = pageDoc.getElementById("searchResult");
     response.close();
     Elements rawShowObjects = results.select("td.vertTh+td");
     TPBToTvShowEpisode makeShows = new TPBToTvShowEpisode();
     List<TvShowEpisode> theShows = makeShows.makeTSEBeans(rawShowObjects);
     DBActions.insertTvEpisodes(theShows, pageURL);
   } catch (MalformedURLException MURLe) {
     // Utilities.sendExceptionEmail(MURLe.getMessage());
     MURLe.printStackTrace();
   } catch (Exception e) {
     // Utilities.sendExceptionEmail(e.getMessage());
     e.printStackTrace();
   }
 }
Exemplo n.º 12
0
 public String getExstention() {
   CloseableHttpClient httpClient = HttpClientBuilder.create().build();
   CloseableHttpResponse response = null;
   try {
     HttpGet httpGet = new HttpGet("http://thepiratebay.org");
     httpGet.addHeader(
         "User-Agent",
         "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36");
     response = httpClient.execute(httpGet);
     Header[] cookieJar = response.getHeaders("set-cookie");
     if (response.getStatusLine().getStatusCode() == 200 && cookieJar.length > 0) {
       for (int i = 0; i < cookieJar.length; i++) {
         String[] cookies = response.getHeaders("set-cookie")[i].getValue().split(";");
         for (int c = 0; c < cookies.length; c++) {
           if (cookies[c].contains("domain=")) {
             return cookies[c].substring(cookies[c].indexOf('=') + 2);
           }
         }
       }
     } else {
       SendMailTLS sendMail = new SendMailTLS();
       sendMail.sendEmail("FAILD TO OBTAIN WEB EXTENTION!", response.toString());
       return "FAIL";
     }
     response.close();
   } catch (Exception e) {
     Utilities.sendExceptionEmail(e.getMessage());
     return e.getMessage();
   }
   return "";
 }
Exemplo n.º 13
0
 public static String uploadMaterial(
     String url, Map<String, String> params, String formDataName, File file) {
   client = getHttpClientInstance();
   URI uri = generateURLParams(url, params);
   HttpPost post = new HttpPost(uri);
   post.setConfig(requestConfig);
   ContentBody contentBody = new FileBody(file);
   HttpEntity reqestEntity =
       MultipartEntityBuilder.create().addPart(formDataName, contentBody).build();
   post.setEntity(reqestEntity);
   String responseStr = null;
   CloseableHttpResponse httpResponse = null;
   try {
     httpResponse = client.execute(post);
     responseStr = generateHttpResponse(httpResponse);
   } catch (IOException e) {
   } finally {
     if (null != httpResponse) {
       try {
         httpResponse.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return responseStr;
 }
  @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();
    }
  }
Exemplo n.º 15
0
  protected byte[] execute(HttpUriRequest request) throws IOException {
    Log.w(TAG, "connecting to " + apn.getMmsc());

    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try {
      client = constructHttpClient();
      response = client.execute(request);

      Log.w(TAG, "* response code: " + response.getStatusLine());

      if (response.getStatusLine().getStatusCode() == 200) {
        return parseResponse(response.getEntity().getContent());
      }
    } catch (NullPointerException npe) {
      // TODO determine root cause
      // see: https://github.com/WhisperSystems/Signal-Android/issues/4379
      throw new IOException(npe);
    } finally {
      if (response != null) response.close();
      if (client != null) client.close();
    }

    throw new IOException("unhandled response code");
  }
Exemplo n.º 16
0
 public static String doPost(String url, Map<String, String> params, String jsonStr) {
   logger.info(jsonStr);
   client = getHttpClientInstance();
   URI uri = generateURLParams(url, params);
   HttpPost post = new HttpPost(uri);
   post.setConfig(requestConfig);
   String responseStr = null;
   CloseableHttpResponse httpResponse = null;
   try {
     HttpEntity entity = new StringEntity(jsonStr, DEFAULT_CHARSET);
     post.setEntity(entity);
     post.setHeader("Content-Type", "application/json");
     httpResponse = client.execute(post);
     responseStr = generateHttpResponse(httpResponse);
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (null != httpResponse) {
       try {
         httpResponse.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return responseStr;
 }
Exemplo n.º 17
0
  public PingInfo ping(String host, int restPort, boolean noProxy) throws Exception {

    PingInfo myPingInfo = pingInfoProvider.createPingInfo();

    RequestConfig.Builder requestConfigBuilder =
        httpClientProvider.createRequestConfigBuilder(host, noProxy);

    String url = String.format(URL_PATTERN, host, restPort) + PingHandler.URL;
    HttpUriRequest request =
        RequestBuilder.post(url)
            .setConfig(requestConfigBuilder.build())
            .addParameter(PingHandler.PING_INFO_INPUT_NAME, gson.toJson(myPingInfo))
            .build();

    CloseableHttpResponse response = httpClientProvider.executeRequest(request);
    try {
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        EntityUtils.consumeQuietly(response.getEntity());
        throw new Exception(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
      }

      HttpEntity entity = response.getEntity();
      String content = EntityUtils.toString(entity);
      EntityUtils.consumeQuietly(entity);
      PingInfo receivedPingInfo = gson.fromJson(content, PingInfo.class);
      receivedPingInfo.getAgentId().setHost(request.getURI().getHost());
      return receivedPingInfo;
    } finally {
      response.close();
    }
  }
 /**
  * A test case for building a model with the given learning algorithm
  *
  * @param algorithmName Name of the learning algorithm
  * @param algorithmType Type of the learning algorithm
  * @throws MLHttpClientException
  * @throws IOException
  * @throws JSONException
  * @throws InterruptedException
  */
 private void buildModelWithLearningAlgorithm(String algorithmName, String algorithmType)
     throws MLHttpClientException, IOException, JSONException, InterruptedException {
   modelName =
       MLTestUtils.createModelWithConfigurations(
           algorithmName,
           algorithmType,
           MLIntegrationTestConstants.RESPONSE_ATTRIBUTE_DIABETES,
           MLIntegrationTestConstants.TRAIN_DATA_FRACTION,
           projectId,
           versionSetId,
           mlHttpclient);
   modelId = mlHttpclient.getModelId(modelName);
   response = mlHttpclient.doHttpPost("/api/models/" + modelId);
   assertEquals(
       "Unexpected response received",
       Response.Status.OK.getStatusCode(),
       response.getStatusLine().getStatusCode());
   response.close();
   // Waiting for model building to end
   boolean status =
       MLTestUtils.checkModelStatusCompleted(
           modelName, mlHttpclient, MLIntegrationTestConstants.THREAD_SLEEP_TIME_LARGE, 1000);
   // Checks whether model building completed successfully
   assertEquals("Model building did not complete successfully", true, status);
 }
Exemplo n.º 19
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;
  }
Exemplo n.º 20
0
 public static void main(String[] args) throws Exception {
   // 豌豆荚捕鱼达人的页面
   String url = "http://www.wandoujia.com/search?key=%E6%8D%95%E9%B1%BC%E8%BE%BE%E4%BA%BA";
   CloseableHttpClient client = HttpClients.createDefault();
   HttpGet httpGet = new HttpGet(url);
   CloseableHttpResponse response = client.execute(httpGet);
   HttpEntity entity = response.getEntity();
   System.out.println("------------------");
   System.out.println(response.getStatusLine());
   LinkFilter filter =
       new LinkFilter() {
         @Override
         public boolean accept(String url) {
           if (url.startsWith("http://www.wandoujia.com")) {
             return true;
           } else {
             return false;
           }
         }
       };
   Set<String> urls =
       HtmlParserTool.extractLinks(EntityUtils.toString(response.getEntity()), filter);
   for (String str : urls) {
     System.out.println(str);
   }
   response.close();
   client.close();
 }
Exemplo n.º 21
0
  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();
        }
      }
    }
  }
  public String DownloadSavePicture(String uri) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    byte[] image = null;
    try {
      // System.out.println(response1.getStatusLine());
      HttpEntity entity1 = response1.getEntity();
      if (entity1 != null) {
        InputStream instreams = entity1.getContent();
        // System.out.println("Do something");
        image = convertStreamToByte(instreams);
      }

    } catch (Exception e) {
      System.out.println("Error in ReadHTML");
    } finally {
      response1.close();
    }
    String uuid = UUID.randomUUID().toString();
    String fileExtension = GetFirstMatchByRegex(uri, "^(.*)\\.(.*?)$", 2);
    String fileName = String.format("%s.%s", uuid, fileExtension);
    String filePath = String.format("%s%s", ConstValue.PICTURE_PATH, fileName);
    File imageFile = new File(filePath);
    FileOutputStream outStream = new FileOutputStream(imageFile);
    outStream.write(image);
    outStream.close();
    return fileName;
  }
  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;
  }
  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();
    }
  }
Exemplo n.º 25
0
 public void close() throws Exception {
   // is.close();
   if (entity != null) {
     EntityUtils.consume(entity);
   }
   response.close();
   httpClient.close();
 }
Exemplo n.º 26
0
 /** Sends a POST request to obtain an access token. */
 private void obtainAccessToken() {
   try {
     token = new OAuth2Token();
     error = new OAuth2Error();
     /* build the request and send it to the token server */
     CloseableHttpClient client = HttpClients.createDefault();
     HttpPost request = new HttpPost(tokenServer);
     request.setEntity(new UrlEncodedFormEntity(Utils.mapToList(tokenParams)));
     CloseableHttpResponse response = client.execute(request);
     HttpEntity entity = response.getEntity();
     /* get the response and parse it */
     JsonParser jp = json.getFactory().createParser(entity.getContent());
     while (jp.nextToken() != null) {
       JsonToken jsonToken = jp.getCurrentToken();
       switch (jsonToken) {
         case FIELD_NAME:
           String name = jp.getCurrentName();
           jsonToken = jp.nextToken();
           if (name.equals("access_token")) {
             token.setAccessToken(jp.getValueAsString());
           } else if (name.equals("token_type")) {
             token.setType(OAuth2TokenType.valueOf(jp.getValueAsString().toUpperCase()));
           } else if (name.equals("expires_in")) {
             token.setExpiresIn(jp.getValueAsInt());
           } else if (name.equals("refresh_token")) {
             token.setRefreshToken(jp.getValueAsString());
           } else if (name.equals("kid")) {
             token.setKeyId(jp.getValueAsString());
           } else if (name.equals("mac_key")) {
             token.setMacKey(jp.getValueAsString());
           } else if (name.equals("mac_algorithm")) {
             token.setMacAlgorithm(jp.getValueAsString());
           } else if (name.equals("error")) {
             error.setType(OAuth2ErrorType.valueOf(jp.getValueAsString().toUpperCase()));
           } else if (name.equals("error_description")) {
             error.setDescription(jp.getValueAsString());
           } else if (name.equals("error_uri")) {
             error.setUri(jp.getValueAsString());
           }
           ready = true;
           break;
         default:
           break;
       }
     }
     jp.close();
     response.close();
     client.close();
   } catch (IOException e) {
     error.setType(OAuth2ErrorType.SERVER_ERROR);
     error.setDescription("Failed to obtain access token from the server.");
   }
   /* notify all waiting objects */
   synchronized (waitObject) {
     ready = true;
     waitObject.notifyAll();
   }
 }
  @Test
  public void testNoContentResponseWithGarbage() throws Exception {
    this.serverBootstrap.setConnectionFactory(new BrokenServerConnectionFactory());
    this.serverBootstrap.registerHandler(
        "/nostuff",
        new HttpRequestHandler() {

          @Override
          public void handle(
              final HttpRequest request, final HttpResponse response, final HttpContext context)
              throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_NO_CONTENT);
          }
        });
    this.serverBootstrap.registerHandler(
        "/stuff",
        new HttpRequestHandler() {

          @Override
          public void handle(
              final HttpRequest request, final HttpResponse response, final HttpContext context)
              throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(new StringEntity("Some important stuff"));
          }
        });

    final HttpHost target = start();
    final HttpGet get1 = new HttpGet("/nostuff");
    final CloseableHttpResponse response1 = this.httpclient.execute(target, get1);
    try {
      Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response1.getStatusLine().getStatusCode());
      EntityUtils.consume(response1.getEntity());
    } finally {
      response1.close();
    }
    final HttpGet get2 = new HttpGet("/stuff");
    final CloseableHttpResponse response2 = this.httpclient.execute(target, get2);
    try {
      Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode());
      EntityUtils.consume(response2.getEntity());
    } finally {
      response2.close();
    }
  }
 @Override
 public void close() {
   try {
     closeableHttpResponse.close();
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   super.close();
 }
Exemplo n.º 29
0
  public static String wechatPost(String url, String params, InputStream keyStream)
      throws Exception {

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    try {
      keyStore.load(keyStream, WeixinConfig.MCH_ID.toCharArray());
    } finally {
      keyStream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext =
        SSLContexts.custom().loadKeyMaterial(keyStore, WeixinConfig.MCH_ID.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(
            sslcontext,
            new String[] {"TLSv1"},
            null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
      String resp = "";

      HttpPost httpPost = new HttpPost(url);
      StringEntity ent = new StringEntity(params, "utf-8");
      ent.setContentType("application/x-www-form-urlencoded");
      httpPost.setEntity(ent);

      CloseableHttpResponse response = httpclient.execute(httpPost);
      try {
        HttpEntity entity = response.getEntity();

        if (entity != null) {
          System.out.println("Response content length: " + entity.getContentLength());
          BufferedReader bufferedReader =
              new BufferedReader(new InputStreamReader(entity.getContent()));
          String text;
          while ((text = bufferedReader.readLine()) != null) {
            resp += text;
          }
        }
        EntityUtils.consume(entity);
        return resp;
      } catch (Exception e) {
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }

    return null;
  }
Exemplo n.º 30
0
 // 通知服务器,让服务器端保存老师数据
 public void serverStoreTeachers() {
   try {
     HttpGet httpGet = new HttpGet("http://10.0.2.2:8080/MyAndroidServer/queryTeacher");
     CloseableHttpResponse response = httpclient.execute(httpGet);
     HttpEntity httpEntity = response.getEntity();
     Log.i("lyj", EntityUtils.toString(httpEntity));
     response.close();
     Log.i("lyj", "inform server to get teachers data");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }