Exemplo n.º 1
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;
    }
  }
Exemplo n.º 2
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;
    }
  }
Exemplo n.º 3
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.º 4
0
  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;
  }
  /**
   * 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.º 6
0
 /** HttpClient 4.3简单入门---HttpPost */
 @Test
 public void test02() {
   HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
   CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
   HttpPost httpPost = new HttpPost(HTTPPOSTTESTURL);
   //		httpPost.setConfig();
   List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数列表
   formParams.add(new BasicNameValuePair("type", "all"));
   formParams.add(new BasicNameValuePair("query", "httpClient"));
   formParams.add(new BasicNameValuePair("sort", ""));
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formParams, "UTF-8");
     httpPost.setEntity(entity);
     HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
     HttpEntity httpEntity = httpResponse.getEntity();
     if (httpEntity != null) {
       logger.info("response:{}", EntityUtils.toString(httpEntity, "UTF-8"));
     }
     closeableHttpClient.close(); // 释放资源
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 /** 使用结束要关闭httpclient */
 public void close() {
   try {
     httpclient.close();
   } catch (IOException e) {
     log.error(e.getMessage());
   }
 }
Exemplo n.º 8
0
  /** HttpClient 4.3 简单入门---HttpGet */
  @Test
  public void test01() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // 创建httpClientBuilder
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); // 创建httpClient
    HttpGet httpGet = new HttpGet(HTTPGETTESTURL);
    logger.info("httpGet.getRequestLine():{}", httpGet.getRequestLine());

    try {
      HttpResponse httpResponse = closeableHttpClient.execute(httpGet); // 执行get请求
      HttpEntity httpEntity = httpResponse.getEntity(); // 获取响应消息实体
      logger.info("响应状态:{}", httpResponse.getStatusLine());
      if (httpEntity != null) {
        logger.info("contentEncoding:{}", httpEntity.getContentEncoding());
        logger.info("response content:{}", EntityUtils.toString(httpEntity));
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        closeableHttpClient.close(); // 关闭流并释放资源
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 @Override
 public void shutdown() throws IOException {
   isShutDown = true;
   httpClient.close();
   scalarMeasurementPool.shutdown();
   offloadingThreadPool.shutdown();
 }
Exemplo n.º 10
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;
  }
Exemplo n.º 11
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.º 12
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");
  }
  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();
    }
  }
  @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();
    }
  }
  @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.º 16
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;
  }
 /** Executes the request against the appliance API (Should not be called directly). */
 @Override
 public MuteCheckResponse executeRequest() throws MorpheusApiRequestException {
   CloseableHttpClient client = null;
   try {
     URIBuilder uriBuilder = new URIBuilder(endpointUrl);
     uriBuilder.setPath("/api/monitoring/checks/" + this.getCheckId() + "/quarantine");
     HttpPut request = new HttpPut(uriBuilder.build());
     this.applyHeaders(request);
     HttpClientBuilder clientBuilder = HttpClients.custom();
     clientBuilder.setDefaultRequestConfig(this.getRequestConfig());
     client = clientBuilder.build();
     request.addHeader("Content-Type", "application/json");
     request.setEntity(new StringEntity(generateRequestBody()));
     CloseableHttpResponse response = client.execute(request);
     return MuteCheckResponse.createFromStream(response.getEntity().getContent());
   } catch (Exception ex) {
     // Throw custom exception
     throw new MorpheusApiRequestException(
         "Error Performing API Request for muting/unmuting a Check", ex);
   } finally {
     if (client != null) {
       try {
         client.close();
       } catch (IOException io) {
         // ignore
       }
     }
   }
 }
Exemplo n.º 18
0
  public static String sendToRockBlockHttp(
      String destImei, String username, String password, byte[] data)
      throws HttpException, IOException {

    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost("https://secure.rock7mobile.com/rockblock/MT");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("imei", destImei));
    urlParameters.add(new BasicNameValuePair("username", username));
    urlParameters.add(new BasicNameValuePair("password", password));
    urlParameters.add(new BasicNameValuePair("data", ByteUtil.encodeToHex(data)));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse response = client.execute(post);

    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }

    try {
      client.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result.toString();
  }
Exemplo n.º 19
0
 /** 断开QHttpClient的连接 */
 public void shutdownConnection() {
   try {
     httpClient.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 20
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;
  }
Exemplo n.º 21
0
 @Override
 public void dispose() {
   try {
     m_httpClient.close();
   } catch (IOException e) {
     m_logger.warn("Dispose SubscriptionPushService", e);
   }
 }
Exemplo n.º 22
0
 public void close() throws Exception {
   // is.close();
   if (entity != null) {
     EntityUtils.consume(entity);
   }
   response.close();
   httpClient.close();
 }
 @Override
 public void cleanUp() {
   LOGGER.info("shutting down SimpleHTTPGetProcessor");
   try {
     httpclient.close();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       httpclient.close();
     } catch (IOException e) {
       e.printStackTrace();
     } finally {
       httpclient = null;
     }
   }
 }
Exemplo n.º 24
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();
   }
 }
Exemplo n.º 25
0
  /**
   * @Title: sendMsg @Description: 发送短信
   *
   * @param @param smsEntity 设定文件
   * @return void 返回类型
   * @throws
   */
  public static void sendMsg(SmsEntity smsEntity) {
    SmsGroup t = new SmsGroup();
    t.seteTime(df.format(smsEntity.getSendTime()));
    t.setInterFaceID(SmsConfig.INTERFACEID);
    t.setLoginName(SmsConfig.LOGIN_NAME);
    t.setLoginPwd(SmsConfig.LOGIN_PWD);
    t.setOpKind(SmsConfig.OPKIND);
    t.setSerType(SmsConfig.SERTYPE);

    SmsTask smsTask = new SmsTask();
    smsTask.setContent(smsEntity.getContent());
    smsTask.setRecivePhoneNumber(smsEntity.getMobile());
    smsTask.setSearchID(smsEntity.getSearchID());

    SmsItem item = new SmsItem();

    List<SmsTask> items = new ArrayList<SmsTask>();
    items.add(smsTask);
    item.setTasks(items);
    t.setItem(item);

    String xml;
    CloseableHttpClient client = null;
    try {
      xml = JaxbUtil.marshToXmlBinding(SmsGroup.class, t);
      client = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(SmsConfig.URL);
      StringEntity requestEntity = new StringEntity(xml, "GB2312");
      httpPost.setEntity(requestEntity);
      CloseableHttpResponse response = client.execute(httpPost);
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        log.info("entity:" + EntityUtils.toString(response.getEntity()));
        log.info(
            "message send sucess:mobile->"
                + smsEntity.getMobile()
                + ",content->"
                + smsEntity.getContent());
      } else {
        throw new RuntimeException("短信发送失败!");
      }
    } catch (JAXBException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (client != null) {
        try {
          client.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
 @Override
 public void run() {
   try {
     httpClient.close();
   } catch (IOException ex) {
     log.error("error closing client", ex);
   }
   httpClient = newClient();
 }
Exemplo n.º 27
0
 /** Stop HTTP client. */
 public void stop() {
   if (httpClient != null) {
     try {
       httpClient.close();
     } catch (IOException ignore) {
       // No-op.
     }
   }
 }
 @Test
 public void testGetRequest() throws IOException {
   CloseableHttpClient httpClient = HttpClients.createDefault();
   HttpGet httpGet = new HttpGet("http://localhost:8080/rest.do");
   CloseableHttpResponse response = httpClient.execute(httpGet);
   System.out.println(EntityUtils.toString(response.getEntity()));
   System.out.println(response.getProtocolVersion());
   System.out.println(response.getStatusLine());
   httpClient.close();
 }
Exemplo n.º 29
0
 private static int openRestURL(String userInfo, int port, String path) throws Exception {
   CloseableHttpClient client = HttpClientBuilder.create().build();
   URI uri = new URI("http", userInfo, "localhost", port, path, null, null);
   HttpGet get = new HttpGet(uri);
   HttpResponse response = client.execute(get);
   int code = response.getStatusLine().getStatusCode();
   EntityUtils.consume(response.getEntity());
   client.close();
   return code;
 }
Exemplo n.º 30
0
 @Override
 public void close() {
   if (httpClient != null) {
     try {
       httpClient.close();
     } catch (IOException e) {
       // Mostly ignore it
       e.printStackTrace();
     }
   }
 }