@Override
  public List<Role> getUserRoles(String userId) throws Exception {
    // Add AuthCache to the execution context
    BasicHttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost("/api/secure/jsonws/role/get-user-roles");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    entity.addPart("userId", new StringBody(userId, Charset.forName("UTF-8")));

    post.setEntity(entity);

    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
    System.out.println("getOrganizationsByUserId Status:[" + resp.getStatusLine() + "]");

    String response = null;
    if (resp.getEntity() != null) {
      response = EntityUtils.toString(resp.getEntity());
    }
    System.out.println("getUserRoles Res:[" + response + "]");

    ArrayList<Role> roles =
        new JSONDeserializer<ArrayList<Role>>().use("values", Role.class).deserialize(response);

    EntityUtils.consume(resp.getEntity());

    return roles;
  }
Пример #2
0
 public void login() throws IOException {
   String checkUrl = "http://web.im.baidu.com/check?callback=_nbc_.f1&v=30&time=" + guid;
   HttpGet getCheck = new HttpGet(checkUrl);
   HttpResponse res1 = httpClient.execute(getCheck);
   System.out.println("Check result: " + EntityUtils.toString(res1.getEntity()));
   EntityUtils.consume(res1.getEntity());
 }
Пример #3
0
  @RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST)
  public String formSubmit(@ModelAttribute User user, Model model)
      throws MalformedURLException, IOException {
    model.addAttribute("user", user);
    HttpPost post =
        new HttpPost(
            "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/");
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName()));
    nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName()));
    nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
    nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
    nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation()));

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

    /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html");
    FileWriter fileWriter = new FileWriter(newTextFile);
    fileWriter.write(response.toString());
    fileWriter.close();*/
    return "result";
  }
Пример #4
0
 /**
  * Get请求
  *
  * @param url
  * @param params
  * @return
  */
 public static String get(String url, List<NameValuePair> params) {
   String body = null;
   try {
     // Get请求
     HttpGet httpget = new HttpGet(url);
     // 设置参数
     String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
     httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
     // 发送请求
     HttpResponse httpresponse = httpClient.execute(httpget);
     // 获取返回数据
     HttpEntity entity = httpresponse.getEntity();
     body = EntityUtils.toString(entity);
     if (entity != null) {
       entity.consumeContent();
     }
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return body;
 }
  /**
   * @param httppost A well-formed {@link HttpUriRequest}
   * @param owlsim An initialized {@link OWLSim} instance. It is expected that the {@link
   *     OWLGraphWrapper} is already loaded with an ontology.
   * @throws Exception
   */
  protected void runServerCommunication(HttpUriRequest httppost, OwlSim owlsim) throws Exception {
    // create server
    Server server = new Server(9031);
    server.setHandler(new OWLServer(g, owlsim));
    try {
      server.start();

      // create a client
      HttpClient httpclient = new DefaultHttpClient();

      // run request
      LOG.info("Executing=" + httppost);
      HttpResponse response = httpclient.execute(httppost);
      LOG.info("Executed=" + httpclient);

      // check response
      HttpEntity entity = response.getEntity();
      StatusLine statusLine = response.getStatusLine();
      LOG.info("Status=" + statusLine.getStatusCode());
      if (statusLine.getStatusCode() == 200) {
        String responseContent = EntityUtils.toString(entity);
        handleResponse(responseContent);
      } else {
        EntityUtils.consumeQuietly(entity);
      }
    } finally {
      // clean up
      server.stop();
    }
  }
Пример #6
0
  protected String convertResponseToString(HttpResponse response, boolean pIgnoreStatus)
      throws IOException {
    int statuscode = response.getStatusLine().getStatusCode();
    if (statuscode != 200 && statuscode != 201 && !pIgnoreStatus) {
      throw new ParseException(
          "server respond with "
              + response.getStatusLine().getStatusCode()
              + ": "
              + EntityUtils.toString(response.getEntity())
              + response.getStatusLine().getStatusCode()
              + ": <unparsable body>");
    }

    HttpEntity entity = response.getEntity();
    if (entity == null) {
      throw new ParseException("http body was empty");
    }
    long len = entity.getContentLength();

    if (len > 2048) {

      throw new ParseException(
          "http body is to big and must be streamed (max is 2048, but was " + len + " byte)");
    }

    String body = EntityUtils.toString(entity, HTTP.UTF_8);
    return body;
  }
Пример #7
0
  public void send(GCMMessage messageBase) throws Exception {
    if (gcmURI == null) {
      throw new Exception("Error sending push. Google cloud messaging properties not provided.");
    }

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

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      HttpEntity entity = response.getEntity();
      String responseMsg = EntityUtils.toString(entity);
      if (response.getStatusLine().getStatusCode() == 200) {
        GCMResponseMessage gcmResponseMessage = gcmResponseReader.readValue(responseMsg);
        if (gcmResponseMessage.failure == 1) {
          if (gcmResponseMessage.results != null && gcmResponseMessage.results.length > 0) {
            throw new Exception(
                "Error sending push. Problem : " + gcmResponseMessage.results[0].error);
          } else {
            throw new Exception("Error sending push. Token : " + messageBase.getToken());
          }
        }
      } else {
        EntityUtils.consume(entity);
        throw new Exception(responseMsg);
      }
    } finally {
      httpPost.releaseConnection();
    }
  }
Пример #8
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;
    }
  }
Пример #9
0
 public static ResponseResult getSSL(String url, String paramsCharset, String resultCharset)
     throws Exception {
   if (url == null || "".equals(url)) {
     return null;
   }
   ResponseResult responseObject = null;
   String responseStr = null;
   HttpClient httpClient = null;
   HttpGet hg = null;
   try {
     httpClient = getNewHttpClient();
     hg = new HttpGet(url);
     HttpResponse response = httpClient.execute(hg);
     if (response != null) {
       responseObject = new ResponseResult();
       responseObject.setUri(hg.getURI().toString());
       responseObject.setStatusCode(response.getStatusLine().getStatusCode());
       if (response.getStatusLine().getStatusCode() == 200) {
         if (resultCharset == null || "".equals(resultCharset)) {
           responseStr = EntityUtils.toString(response.getEntity(), LSystem.encoding);
         } else {
           responseStr = EntityUtils.toString(response.getEntity(), resultCharset);
         }
       } else {
         responseStr = null;
       }
       responseObject.setResult(responseStr);
     }
   } catch (Exception e) {
     throw new Exception(e.getMessage());
   } finally {
     abortConnection(hg, httpClient);
   }
   return responseObject;
 }
  public static void test1() throws ClientProtocolException, IOException {
    // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("username", ""));
    formparams.add(new BasicNameValuePair("areacode", "86"));
    formparams.add(new BasicNameValuePair("telephone", "18782071219"));
    formparams.add(new BasicNameValuePair("remember_me", "1"));
    formparams.add(new BasicNameValuePair("password", Encoding.MD5("199337").toUpperCase()));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost("http://xueqiu.com/user/login");
    httppost.setEntity(entity);
    httppost.setHeader("X-Requested-With", "XMLHttpRequest");
    CloseableHttpResponse httpResponse = httpClient.execute(httppost);
    HttpEntity entity1 = httpResponse.getEntity();
    if (entity1 != null) {
      System.out.println("--------------------------------------");
      System.out.println("Response content: " + EntityUtils.toString(entity1, "UTF-8"));
      System.out.println("--------------------------------------");
    }
    setCookieStore(httpResponse);
    HttpGet httpGet =
        new HttpGet(
            "http://xueqiu.com/financial_product/query.json?page=1&size=3&order=desc&orderby=SALEBEGINDATE&status=1&_=1439607538138");

    httpResponse = httpClient.execute(httpGet);
    entity1 = httpResponse.getEntity();
    if (entity1 != null) {
      System.out.println("--------------------------------------");
      System.out.println("Response content: " + EntityUtils.toString(entity1, "UTF-8"));
      System.out.println("--------------------------------------");
    }
  }
  private void retract()
      throws Exception, UnsupportedEncodingException, IOException, InterruptedException {

    HttpPost postStart = new HttpPost(BASE_URL + "/youtube/retract");
    ArrayList<NameValuePair> formParams = new ArrayList<NameValuePair>();

    formParams.add(new BasicNameValuePair("mediapackage", getSampleMediaPackage()));
    formParams.add(new BasicNameValuePair("elementId", "track-1"));
    postStart.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

    // Ensure we get a 200 OK
    HttpResponse response = client.execute(postStart);
    Assert.assertEquals("Error during retract", 200, response.getStatusLine().getStatusCode());

    String jobXML = EntityUtils.toString(response.getEntity());
    long jobId = getJobId(jobXML);

    // Check if job is finished
    // Ensure that the job finishes successfully
    int attempts = 0;
    while (true) {
      if (++attempts == 20) Assert.fail("ServiceRegistry rest endpoint test has hung");
      HttpGet getJobMethod = new HttpGet(BASE_URL + "/services/job/" + jobId + ".xml");
      String getResponse = EntityUtils.toString(client.execute(getJobMethod).getEntity());
      String state = getJobStatus(getResponse);
      if ("FINISHED".equals(state)) break;
      if ("FAILED".equals(state))
        Assert.fail("Retract from youtube failed! (Job " + jobId + "). Do it manually for video!");
      System.out.println("Job " + jobId + " is " + state);
      Thread.sleep(5000);
    }
  }
  public Organization getOrganizationById(String portalOrgId) throws Exception {
    // Add AuthCache to the execution context
    BasicHttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost("/api/secure/jsonws/organization/get-organization");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("organizationId", portalOrgId));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);

    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
    System.out.println("getOrganizationById Status:[" + resp.getStatusLine() + "]");

    String response = null;
    if (resp.getEntity() != null) {
      response = EntityUtils.toString(resp.getEntity());
    }
    System.out.println("getOrganizationById Res:[" + response + "]");

    Organization org =
        new JSONDeserializer<Organization>().deserialize(response, Organization.class);

    EntityUtils.consume(resp.getEntity());

    return org;
  }
  @Override
  public void setUserRole(String userId, String roleId) throws Exception {
    // Add AuthCache to the execution context
    BasicHttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost("/api/secure/jsonws//user/set-role-users");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("roleId", roleId));
    params.add(new BasicNameValuePair("userIds", userId));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);

    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
    System.out.println("getOrganizationsByUserId Status:[" + resp.getStatusLine() + "]");

    String response = null;
    if (resp.getEntity() != null) {
      response = EntityUtils.toString(resp.getEntity());
    }
    System.out.println("setUserRole Res:[" + response + "]");

    EntityUtils.consume(resp.getEntity());
  }
  @Override
  public boolean userHasRole(String userId, String roleName) throws Exception {
    // Add AuthCache to the execution context
    BasicHttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost("/api/secure/jsonws/role/has-user-role");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    entity.addPart("userId", new StringBody(userId, Charset.forName("UTF-8")));
    entity.addPart("companyId", new StringBody(companyId, Charset.forName("UTF-8")));
    entity.addPart("name", new StringBody(roleName, Charset.forName("UTF-8")));
    entity.addPart("inherited", new StringBody("false", Charset.forName("UTF-8")));

    post.setEntity(entity);

    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
    System.out.println("userHasRole Status:[" + resp.getStatusLine() + "]");

    String response = null;
    if (resp.getEntity() != null) {
      response = EntityUtils.toString(resp.getEntity());
    }
    System.out.println("userHasRole Res:[" + response + "]");

    JSONDeserializer<Boolean> deserializer = new JSONDeserializer<Boolean>();
    Boolean hasRole = deserializer.deserialize(response, Boolean.class);

    EntityUtils.consume(resp.getEntity());

    return hasRole;
  }
Пример #15
0
  public void run() {
    for (Object MSISDN : mListMSISDN) {
      String TextResponse = "";

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

      HttpPost mPost = new HttpPost(URL);

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

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

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

        System.out.println(TextResponse);

        EntityUtils.consume(entity);
      } catch (Exception ex) {
        mLog.log.error(ex);
      } finally {
        mLog.log.debug("REQUEST --> " + XMLReqeust);
        mLog.log.debug("RESPONSE --> " + TextResponse);
      }
    }
    mLog.log.debug("KET THUC THEAD " + ThreadIndex);
  }
 @Override
 public String getChannels(String serverUrl, boolean premium)
     throws ClientProtocolException, UnsupportedEncodingException, IOException {
   String playLIst = null;
   CloseableHttpClient httpClient = HttpClientBuilder.create().build();
   // CloseableHttpClient httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build();
   HttpResponse login = httpClient.execute(getVideoStarLogin());
   EntityUtils.consume(login.getEntity());
   if (login.getStatusLine().getStatusCode() == 302) {
     HttpResponse getChannel = httpClient.execute(getChannelsRequest(login));
     if (getChannel.getStatusLine().getStatusCode() == 200) {
       VideoStarChannelRequest channels =
           jsonService.parseVideoStarChannels(EntityUtils.toString(getChannel.getEntity()));
       if (channels != null && channels.getStatus().equals("ok")) {
         return prepareChannelList(channels, serverUrl, premium);
         // return channelsString;
       } else if (channels != null && channels.getStatus().equals("error")) {
         // TODO
       } else {
         // TODO
       }
     }
   }
   return playLIst;
 }
  @Override
  public void execute() throws Exception {
    int statusCode = 0, triesCount = 0;
    HttpResponse response = null;
    logger.info("Sending bulk request to elasticsearch cluster");

    String entity;
    synchronized (bulkBuilder) {
      entity = bulkBuilder.toString();
      bulkBuilder = new StringBuilder();
    }

    while (statusCode != HttpStatus.SC_OK && triesCount < serversList.size()) {
      triesCount++;
      String host = serversList.get();
      String url = host + "/" + BULK_ENDPOINT;
      HttpPost httpRequest = new HttpPost(url);
      httpRequest.setEntity(new StringEntity(entity));
      response = httpClient.execute(httpRequest);
      statusCode = response.getStatusLine().getStatusCode();
      logger.info("Status code from elasticsearch: " + statusCode);
      if (response.getEntity() != null)
        logger.debug(
            "Status message from elasticsearch: "
                + EntityUtils.toString(response.getEntity(), "UTF-8"));
    }

    if (statusCode != HttpStatus.SC_OK) {
      if (response.getEntity() != null) {
        throw new EventDeliveryException(EntityUtils.toString(response.getEntity(), "UTF-8"));
      } else {
        throw new EventDeliveryException("Elasticsearch status code was: " + statusCode);
      }
    }
  }
Пример #18
0
 public void testConsumeContent() throws Exception {
   String s = "Message content";
   StringEntity httpentity = new StringEntity(s);
   HttpEntityWrapper wrapped = new HttpEntityWrapper(httpentity);
   EntityUtils.consume(wrapped);
   EntityUtils.consume(wrapped);
 }
  @Override
  public final HttpResponse invoke(Q query, String endpoint) throws InvocationException {
    Preconditions.checkNotNull(query);
    Preconditions.checkNotNull(endpoint);

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

      org.apache.http.HttpResponse httpResponse = httpClient.execute(method);
      response = httpResponse.getEntity();
      return HttpResponse.create(
          httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(response));
    } catch (Exception e) {
      if (method != null) {
        log.debug(
            "Error during invocation with URL: "
                + method.getURI()
                + ", endpoint: "
                + endpoint
                + ", query: "
                + query,
            e);
      } else {
        log.debug("Error during invocation with: endpoint: " + endpoint + ", query: " + query, e);
      }
      throw new InvocationException("InvocationException : ", e);
    } finally {
      EntityUtils.consumeQuietly(response);
    }
  }
Пример #20
0
  /**
   * proxy query log for the specified task.
   *
   * @param task the specified task
   */
  private void listLogs() {

    // PROXY_URL = "http://%s:%s/logview?%s=%s";
    String url =
        String.format(
            PROXY_URL,
            host,
            port,
            HttpserverUtils.HTTPSERVER_LOGVIEW_PARAM_CMD,
            HttpserverUtils.HTTPSERVER_LOGVIEW_PARAM_CMD_LIST);
    try {
      // 1. proxy call the task host log view service
      HttpClient client = HttpClientBuilder.create().build();
      HttpPost post = new HttpPost(url);
      HttpResponse response = client.execute(post);

      // 2. check the request is success, then read the log
      if (response.getStatusLine().getStatusCode() == 200) {
        String data = EntityUtils.toString(response.getEntity());

        parseString(data);

      } else {
        String data = EntityUtils.toString(response.getEntity());
        summary = ("Failed to get files\n" + data);
      }
    } catch (Exception e) {
      summary = ("Failed to get files\n" + e.getMessage());
      LOG.error(e.getCause(), e);
    }
  }
Пример #21
0
  public static String postJSON(final String url, JSONObject params, final String headValue)
      throws Exception {
    HttpPost httpRequest = new HttpPost(url);
    if (headValue != null) {
      httpRequest.setHeader(CUSTOM_HEAD_NAME, headValue);
    }
    httpRequest.setHeader("Content-Type", CONTENT_TYPE);
    httpRequest.setEntity(new StringEntity(params.toString(), HTTP.UTF_8));
    HttpResponse httpResponse;

    try {
      httpResponse = HttpManager.execute(httpRequest);
    } catch (SocketException e) {
      httpResponse = HttpManager.execute(httpRequest);
    }
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode == 200) {
      return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
    } else if (statusCode == 302) {
      throw new IOException("302");
    } else {
      String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
      throw new ApiRequestErrorException(result);
    }
  }
Пример #22
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();
    }
  }
Пример #23
0
  public static boolean uploadFile(
      String url, String uploadKey, File file, Map<String, String> params) {
    // TODO httpClient连接关闭问题需要考虑
    try {
      HttpPost httppost = new HttpPost("http://www.new_magic.com/service.php");

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

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

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

        Map<String, Object> responseMap = JsonUtil.parseJson(body, Map.class);
        if (responseMap.containsKey("code") && responseMap.get("code").equals(10000)) {
          return true;
        }
      }
    } catch (Exception e) {
      log.error("", e);
    }
    return false;
  }
  @Test
  public void testBasicAuthenticationCredentialsCaching() throws Exception {
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

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

    TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy();

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

    HttpContext context = new BasicHttpContext();

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

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

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

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

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

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

      if (sequence > 4) {
        break;
      }
    }
  }
  public static String get(String url, List<NameValuePair> params) {
    String body = null;
    try {
      HttpClient hc = new DefaultHttpClient();
      // Get请求
      HttpGet httpget = new HttpGet(url);
      // 设置参数
      String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
      httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
      // 设置请求和传输超时时间
      RequestConfig requestConfig =
          RequestConfig.custom().setSocketTimeout(4000).setConnectTimeout(4000).build();
      httpget.setConfig(requestConfig);
      // 发送请求
      HttpResponse httpresponse = hc.execute(httpget);
      // 获取返回数据
      HttpEntity entity = httpresponse.getEntity();
      body = EntityUtils.toString(entity);

      if (entity != null) {
        entity.consumeContent();
      }
    } catch (Exception e) {
      logger.error("http的get方法" + e.toString());
      throw new RuntimeException(e);
    }
    return body;
  }
Пример #27
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;
  }
Пример #28
0
  public LocalDocument getDocument(LocalQuery query, boolean recurring) throws IOException {
    HttpResponse response;
    if (recurring) {
      response = core.post(getRecurringUrl, query.toJson());
    } else {
      response = core.post(getUrl, query.toJson());
    }

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      LocalDocument ld;
      try {
        ld = new LocalDocument(EntityUtils.toString(response.getEntity()));
      } catch (JsonException e) {
        throw new IOException(e);
      }
      InternalLogger.debug("Received document with ID " + ld.getID());
      currentDocument = ld;
      return ld;
    } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
      InternalLogger.debug("No document found matching query");
      EntityUtils.consume(response.getEntity());
      return null;
    } else {
      logUnexpected(response);
      return null;
    }
  }
  public byte[] handleResponse(HttpResponse hr) throws ClientProtocolException, IOException {
    if (hr.getStatusLine().getStatusCode() == 200) {
      if (hr.getEntity().getContentEncoding() == null) {
        return EntityUtils.toByteArray(hr.getEntity());
      }

      if (hr.getEntity().getContentEncoding().getValue().contains("gzip")) {
        GZIPInputStream gis = null;
        try {
          gis = new GZIPInputStream(hr.getEntity().getContent());
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          byte[] b = new byte[1024];
          int n;
          while ((n = gis.read(b)) != -1) baos.write(b, 0, n);
          System.out.println("Gzipped");
          return baos.toByteArray();
        } catch (IOException e) {
          throw e;
        } finally {
          try {
            if (gis != null) gis.close();
          } catch (IOException ex) {
            throw ex;
          }
        }
      }
      return EntityUtils.toByteArray(hr.getEntity());
    }

    if (hr.getStatusLine().getStatusCode() == 302) {
      throw new IOException("302");
    }
    return null;
  }
  private Role getRoleByName(String name) throws ParseException, IOException {
    // Add AuthCache to the execution context
    BasicHttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost("/api/secure/jsonws//role/get-role");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("companyId", companyId));
    params.add(new BasicNameValuePair("name", name));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);

    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
    System.out.println("getRoleById Status:[" + resp.getStatusLine() + "]");

    String response = null;
    if (resp.getEntity() != null) {
      response = EntityUtils.toString(resp.getEntity());
    }

    Role role = null;
    if (!StringUtil.contains(response, "NoSuch", "")
        && !StringUtil.contains(response, "exception", "")) {
      JSONDeserializer<Role> deserializer = new JSONDeserializer<Role>();
      role = deserializer.deserialize(response, Role.class);
    }

    EntityUtils.consume(resp.getEntity());

    return role;
  }