Exemplo n.º 1
1
  public String sendLoginData(LoginData data) {

    String responseMessage = null;

    try {

      System.out.println("SENDING >>>>>>>>>");

      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://system.smartsales.bg/user/android_login/");

      // Add your data
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

      nameValuePairs.add(new BasicNameValuePair("email", data.getEmail()));

      nameValuePairs.add(new BasicNameValuePair("password", data.getPassword()));

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);

      responseMessage = EntityUtils.toString(response.getEntity());

    } catch (Exception e) {
      e.printStackTrace();
    }

    return responseMessage;
  }
  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 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("--------------------------------------");
    }
  }
  @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);
      }
    }
  }
  public void reqGET(URL url) {
    try {

      try {

        HttpClient client = new DefaultHttpClient();
        String postURL = "http://192.168.0.5:8080/HearingEducationServer/HearingServer";
        HttpPost post = new HttpPost(postURL);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("registerId", "kris"));
        params.add(new BasicNameValuePair("registerPass", "xyz"));
        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        post.setEntity(ent);
        HttpResponse responsePOST = client.execute(post);
        HttpEntity resEntity = responsePOST.getEntity();
        if (resEntity != null) {
          Log.i("RESPONSE", EntityUtils.toString(resEntity));
        } else {
          Log.i("RESPONSE ERROR", EntityUtils.toString(resEntity));
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 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;
  }
Exemplo n.º 7
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;
 }
Exemplo n.º 8
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);
    }
  }
  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;
  }
Exemplo n.º 10
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);
    }
  }
Exemplo n.º 11
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;
 }
Exemplo n.º 12
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.º 13
0
  public static final String upLoadPic2Server(String picPath, String board, Context context)
      throws IOException {
    if (picPath == null || picPath.length() == 0) {
      return "";
    }
    LoginInfo loginInfo = LoginInfo.getInstance(context);
    File file = new File(compressBitmapByPath(picPath));
    HttpClient client;
    BasicHttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);
    client = new DefaultHttpClient(httpParameters);
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    String url =
        "http://bbs.nju.edu.cn/"
            + loginInfo.getLoginCode()
            + "/bbsdoupload?ptext=text&board="
            + board;
    HttpPost imgPost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("up", new FileBody(file));
    reqEntity.addPart("exp", new StringBody("", Charset.forName("GB2312")));
    reqEntity.addPart("ptext", new StringBody("text", Charset.forName("GB2312")));
    reqEntity.addPart("board", new StringBody(board, Charset.forName("GB2312")));
    imgPost.setEntity(reqEntity);
    imgPost.addHeader("Cookie", loginInfo.getLoginCookie());
    imgPost.addHeader(reqEntity.getContentType());

    String result;
    HttpResponse httpResponse;
    httpResponse = client.execute(imgPost);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
      result = EntityUtils.toString(httpResponse.getEntity());
      result = result.substring(result.indexOf("url=") + 2, result.indexOf(">") - 1);
      String fileNum = result.substring(result.indexOf("file=") + 5, result.indexOf("&name"));
      String fileName = file.getName();
      if (fileName.length() > 10) {
        fileName = fileName.substring(fileName.length() - 10);
      }
      url =
          "http://bbs.nju.edu.cn/"
              + loginInfo.getLoginCode()
              + "/bbsupload2?board="
              + board
              + "&file="
              + fileNum
              + "&name="
              + fileName
              + "&exp=&ptext=text";
      HttpGet uploadGet = new HttpGet(url);
      uploadGet.addHeader("Cookie", loginInfo.getLoginCookie());
      httpResponse = client.execute(uploadGet);
      if (httpResponse.getStatusLine().getStatusCode() == 200) {
        result = EntityUtils.toString(httpResponse.getEntity());
        return result.substring(result.indexOf("'\\n") + 3, result.indexOf("\\n'"));
      }
    }
    return null;
  }
Exemplo n.º 14
0
 @Override
 protected String doInBackground(String... urls) {
   HttpClient httpClient = new DefaultHttpClient();
   Log.d("inbgactivity", urls[0]);
   if (networkStatus() == NETWORK_STATUS_OK) {
     if (method.equalsIgnoreCase("POST")) {
       try {
         HttpPost request = new HttpPost(urls[0]);
         Log.d("asd", this.params);
         StringEntity parameters = new StringEntity(params);
         request.addHeader("content-type", "application/json");
         request.setEntity(parameters);
         HttpResponse response = httpClient.execute(request);
         return EntityUtils.toString(response.getEntity());
       } catch (Exception e) {
         e.printStackTrace();
         Log.d("bg exception", e.toString());
         return null;
       }
     } else if (method.equalsIgnoreCase("GET")) {
       try {
         HttpGet request = new HttpGet(urls[0]);
         HttpResponse response = httpClient.execute(request);
         return EntityUtils.toString(response.getEntity());
       } catch (Exception e) {
         e.printStackTrace();
         Log.d("bg exception", e.toString());
         return null;
       }
     } else if (method.equalsIgnoreCase("OAUTH_GET")) {
       try {
         OAuthConsumer consumer = new DefaultOAuthConsumer(LINKEDIN_API_KEY, LINKEDIN_SECRET_KEY);
         consumer.setTokenWithSecret(urls[1], urls[2]);
         URL url = new URL(urls[0]);
         HttpURLConnection request = (HttpURLConnection) url.openConnection();
         request.setRequestMethod("GET");
         request.setUseCaches(true);
         consumer.sign(request);
         request.connect();
         BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
         StringBuilder sb = new StringBuilder();
         String line;
         while ((line = br.readLine()) != null) {
           sb.append(line + "\n");
         }
         br.close();
         Log.d("as", sb.toString());
         return sb.toString();
       } catch (Exception e) {
         e.printStackTrace();
         Log.d("bg exception", e.toString());
         return null;
       }
     } else return null;
   } else {
     return null;
   }
 }
Exemplo n.º 15
0
  /**
   * Creates request against SPNEGO protected web-app with FORM fallback. It doesn't try to login
   * using SPNEGO - it uses FORM authn directly.
   *
   * @param contextUrl
   * @param page
   * @param user
   * @param pass
   * @param expectedStatusCode
   * @return
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeHttpCallWoSPNEGO(
      final String contextUrl,
      final String page,
      final String user,
      final String pass,
      final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.info("Requesting URL: " + url);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(REDIRECT_STRATEGY);
    String unauthorizedPageBody = null;
    try {
      final HttpGet httpGet = new HttpGet(url);
      HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      unauthorizedPageBody = EntityUtils.toString(response.getEntity());

      assertNotNull(unauthorizedPageBody);
      LOGGER.info(unauthorizedPageBody);
      assertTrue(unauthorizedPageBody.contains("j_security_check"));

      HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("j_username", user));
      nameValuePairs.add(new BasicNameValuePair("j_password", pass));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      response = httpClient.execute(httpPost);
      statusCode = response.getStatusLine().getStatusCode();
      assertEquals(
          "Unexpected status code returned after the authentication.",
          expectedStatusCode,
          statusCode);
      return EntityUtils.toString(response.getEntity());
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Exemplo n.º 16
0
  /**
   * @param url
   * @param paramMap 不定长度 如果长度为2则head+params,否则param
   */
  public static String returnGet(String url, JSONObject... paramList) {
    HttpClient httpclient = new DefaultHttpClient();
    JSONObject headMap = null;
    JSONObject paramMap = null;
    String result = "";
    try {
      HttpGet httpget = new HttpGet(url);
      //			httpget=setBrowHead(httpget);
      if (paramList == null || paramList.length == 0) {

      } else if (paramList.length == 1) {
        paramMap = paramList[0];
      } else if (paramList.length == 2) {
        headMap = paramList[0];
        paramMap = paramList[1];
      }

      if (headMap != null && headMap.size() > 0) {
        for (Entry entry : headMap.entrySet()) {
          httpget.setHeader(entry.getKey().toString(), entry.getValue().toString());
        }
      }

      if (paramMap != null && paramMap.size() > 0) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Entry entry : paramMap.entrySet()) {
          params.add(
              new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
        }
        String str = EntityUtils.toString(new UrlEncodedFormEntity(params, "utf-8"));
        httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
      }
      // 执行get请求.
      HttpResponse response = httpclient.execute(httpget);
      // 获取响应实体
      HttpEntity entity = response.getEntity();
      try {
        System.out.println("--------------------------------------");
        // 打印响应状态
        System.out.println(response.getStatusLine());
        if (entity != null) {
          // 打印响应内容长度
          System.out.println("Response content length: " + entity.getContentLength());
          result = EntityUtils.toString(entity);
          // 打印响应内容
          System.out.println("Response content: " + result);
        }
        System.out.println("------------------------------------");
      } finally {
        httpget.releaseConnection();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
Exemplo n.º 17
0
  public static String executeGet(
      String httpUrl, Map<String, String> param, HttpClient httpClient, String chartEncoding) {
    String result = "";

    try {
      if (StringUtils.isBlank(chartEncoding)) {
        chartEncoding = DEFAULT_CHARENCODING;
      }

      List<NameValuePair> params = null;

      if (param != null && !param.isEmpty()) {
        params = new ArrayList<>(param.size());

        for (String paramName : param.keySet()) {
          params.add(new BasicNameValuePair(paramName, param.get(paramName)));
        }
      }

      HttpGet httpGet = new HttpGet();

      // 设置请求配置
      setRequestConfig(httpGet);

      // 设置请求参数
      String fullUrl = httpUrl;
      if (params != null && !param.isEmpty()) {
        String queryStrings = EntityUtils.toString(new UrlEncodedFormEntity(params, chartEncoding));

        if (httpUrl.indexOf("?") != -1) {
          fullUrl += "&" + queryStrings;
        } else {
          fullUrl += "?" + queryStrings;
        }
      }

      httpGet.setURI(new URI(fullUrl));

      logger.debug("准备调用远程服务[ GET ], url: {}", fullUrl);

      HttpResponse httpResponse = httpClient.execute(httpGet);

      // 获取返回数据
      HttpEntity entity = httpResponse.getEntity();
      result = EntityUtils.toString(entity, chartEncoding);
      if (entity != null) {
        EntityUtils.consume(entity);
      }
    } catch (Exception ex) {
      logger.error("请求失败,request: {},param:{}", httpUrl, param);
      throw new RuntimeException("发送HTTP Get请求失败", ex);
    }

    return result;
  }
Exemplo n.º 18
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;
    }
  }
  @Override
  public void login() {
    loginsuccessful = false;
    try {
      initialize();

      NULogger.getLogger().info("Trying to log in to TopUpload1.com");
      httpPost = new NUHttpPost("http://topupload1.com/ajax/_account_login.ajax.php");

      List<NameValuePair> formparams = new ArrayList<NameValuePair>();
      formparams.add(new BasicNameValuePair("username", getUsername()));
      formparams.add(new BasicNameValuePair("password", getPassword()));

      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
      httpPost.setEntity(entity);
      httpResponse = httpclient.execute(httpPost, httpContext);
      NULogger.getLogger().info(httpResponse.getStatusLine().toString());
      responseString = EntityUtils.toString(httpResponse.getEntity());

      if (StringUtils.stringBetweenTwoStrings(responseString, "\"login_status\":\"", "\"")
          .equals("success")) {
        EntityUtils.consume(httpResponse.getEntity());
        loginsuccessful = true;
        username = getUsername();
        password = getPassword();
        NULogger.getLogger().info("TopUpload1.com login successful!");

      } else {
        // Get error message
        responseString = EntityUtils.toString(httpResponse.getEntity());
        // FileUtils.saveInFile("TopUploadOneAccount.html", responseString);
        Document doc = Jsoup.parse(responseString);
        String error = doc.select(".err").first().text();

        if ("Incorrect Login or Password".equals(error)) {
          throw new NUInvalidLoginException(getUsername(), HOSTNAME);
        }

        // Generic exception
        throw new Exception("Login error: " + error);
      }
    } catch (NUException ex) {
      resetLogin();
      ex.printError();
      accountUIShow().setVisible(true);
    } catch (Exception e) {
      resetLogin();
      NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] {getClass().getName(), e});
      showWarningMessage(Translation.T().loginerror(), HOSTNAME);
      accountUIShow().setVisible(true);
    }
  }
  @Test
  public void misplacedParametersDoNotEffectResponse() throws IOException {
    HttpResponse baseResp =
        OSLCUtils.getResponseFromUrl(
            baseUrl, currentUrl, basicCreds, OSLCConstants.CT_DISC_CAT_XML);
    String baseRespValue = EntityUtils.toString(baseResp.getEntity());

    HttpResponse parameterResp =
        OSLCUtils.getResponseFromUrl(
            baseUrl, currentUrl + "?oslc_cm:query", basicCreds, OSLCConstants.CT_DISC_CAT_XML);
    String parameterRespValue = EntityUtils.toString(parameterResp.getEntity());

    assertTrue(baseRespValue.equals(parameterRespValue));
  }
Exemplo n.º 21
0
  public void testSOAPCall() throws Exception {

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

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

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

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

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

    // -----------------------------------------------------
    // Upload the video to youtube
    // -----------------------------------------------------

    HttpPost postStart = new HttpPost(BASE_URL + "/youtube/");
    List<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("Upload to youtube failed!", 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");
      jobXML = EntityUtils.toString(client.execute(getJobMethod).getEntity());
      String state = getJobStatus(jobXML);
      if ("FINISHED".equals(state)) {
        // Get Mediapackage Track from flavor youtube/watchpage
        String payload = getPayloadFromJob(jobXML);
        String youtubeXmlUrl = getYoutubeURL(payload);
        HttpURLConnection connection = (HttpURLConnection) new URL(youtubeXmlUrl).openConnection();
        Assert.assertEquals(
            "Url status code from uploaded video is not 200", 200, connection.getResponseCode());
        break;
      }
      if ("FAILED".equals(state)) Assert.fail("Job " + jobId + " failed");
      System.out.println("Job " + jobId + " is " + state);
      Thread.sleep(5000);
    }

    // -----------------------------------------------------
    // Retract the video from youtube
    // -----------------------------------------------------

    retract();
  }
Exemplo n.º 23
0
  @Override
  protected TestResult testSite(Site site, TestResult testResult) throws Throwable {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    String responseBody = "";
    String responseBody2 = "";

    try {
      HttpGet request =
          new HttpGet(site.getAddress() + "j_security_check?username=guest&password=%E6%E6%27");
      HttpResponse response = httpclient.execute(request);
      int statusCode = response.getStatusLine().getStatusCode();
      HttpEntity entity = response.getEntity();
      responseBody = EntityUtils.toString(entity);

      if (responseBody.contains("Exception")
          || responseBody.contains("exception")
          || responseBody.contains("Caused by")
          || responseBody.contains("caused by")) {
        testResult.setPassed(false);
        testResult.setMessage("Your application has improper error handling!");
      } else if (statusCode == 500 || statusCode == 200) {

        HttpGet request2 = new HttpGet(site.getAddress() + "...");
        HttpResponse response2 = httpclient.execute(request2);
        int statusCode2 = response2.getStatusLine().getStatusCode();
        HttpEntity entity2 = response2.getEntity();
        responseBody2 = EntityUtils.toString(entity2);
        if (responseBody2.contains("Jetty") || responseBody2.contains("jetty")) {
          testResult.setPassed(false);
          testResult.setMessage(
              "Your application has improved error handling, but still leaks information!");
        } else if (statusCode2 == 404 || statusCode2 == 200) {
          testResult.setPassed(true);
          testResult.setMessage(
              "Ok, your application handles errors codes and tries not to leak information!");
        }
      } else {
        testResult.setPassed(false);
        testResult.setMessage(
            "The test didn't work properly, are you providing a proper and secure error handling?");
      }
    } finally {
      httpclient.getConnectionManager().shutdown();
    }

    return testResult;
  }
  protected String execute(HttpRequestBase httpRequestBase)
      throws CredentialException, IOException {

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {
      if (_closeableHttpClient == null) {
        afterPropertiesSet();
      }

      HttpResponse httpResponse = _closeableHttpClient.execute(httpHost, httpRequestBase);

      StatusLine statusLine = httpResponse.getStatusLine();

      if (statusLine.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {

        if (_logger.isWarnEnabled()) {
          _logger.warn("Status code " + statusLine.getStatusCode());
        }

        return null;
      } else if (statusLine.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {

        throw new CredentialException("Not authorized to access JSON web service");
      } else if (statusLine.getStatusCode() == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {

        throw new JSONWebServiceUnavailableException("Service unavailable");
      }

      return EntityUtils.toString(httpResponse.getEntity(), Charsets.UTF_8);
    } finally {
      httpRequestBase.releaseConnection();
    }
  }
  @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.º 26
0
  @Override
  public Boolean doInBackground(String... urls) {
    try {

      // ------------------>>
      HttpGet httppost = new HttpGet(urls[0]);
      HttpClient httpclient = new DefaultHttpClient();
      HttpResponse response = httpclient.execute(httppost);

      // StatusLine stat = response.getStatusLine();
      int status = response.getStatusLine().getStatusCode();
      Log.e("status", status + "");

      if (status == 200) {
        HttpEntity entity = response.getEntity();
        data = EntityUtils.toString(entity);

        return true;
      }

      // ------------------>>

    } catch (IOException e) {
      e.printStackTrace();
    }
    return false;
  }
Exemplo n.º 27
0
    public JSONObject getJSONFromURL() {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);

      HttpResponse response;
      HttpClient myClient = new DefaultHttpClient();
      HttpPost myConnection = new HttpPost(urlIan);

      try {
        response = myClient.execute(myConnection);
        test = EntityUtils.toString(response.getEntity(), "UTF-8");
        arr = new JSONArray(test);
        strRoot = arr.getJSONObject(0);
        finished = true;

      } catch (IOException e) {
        // Toast.makeText(getApplicationContext(), "error1: "+e.toString(),
        // Toast.LENGTH_LONG).show();
      } catch (JSONException e) {
        // Toast.makeText(getApplicationContext(), "error2: "+e.toString(),
        // Toast.LENGTH_LONG).show();
      }

      startProgressBar();
      return strRoot;
    }
Exemplo n.º 28
0
  public String postUser(String username) {
    String uri = "http://10.0.2.2:8090/user";
    List<NameValuePair> passParams = new ArrayList<NameValuePair>(1);
    passParams.add(new BasicNameValuePair("username", username));
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(uri);
    // Log.d("loltale:params", Integer.toString(params.length));

    try {
      httpPost.setEntity(new UrlEncodedFormEntity(passParams));
      HttpResponse response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();

      if (entity != null) {
        return EntityUtils.toString(entity);
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Exemplo n.º 29
0
  private String doGet(String url) {
    String responseStr = "";
    try {
      HttpGet httpRequest = new HttpGet(url);
      HttpParams params = new BasicHttpParams();
      ConnManagerParams.setTimeout(params, 1000);
      HttpConnectionParams.setConnectionTimeout(params, 3000);
      HttpConnectionParams.setSoTimeout(params, 5000);
      httpRequest.setParams(params);

      HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
      final int ret = httpResponse.getStatusLine().getStatusCode();
      if (ret == HttpStatus.SC_OK) {
        responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
      } else {
        responseStr = "-1";
      }
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return responseStr;
  }
    //	通知センターに通知を残す(pecoriできる人がいます)
    private void notifyNearUser(HttpResponse res) throws Exception {
      String body = EntityUtils.toString(res.getEntity(), "UTF-8");
      JSONObject json = new JSONObject(body.toString());
      JSONArray nearUsers = json.getJSONArray("near_users");
      for (int i = 0; i < nearUsers.length(); i++) {
        JSONObject user = nearUsers.getJSONObject(i);
        String facebookId = user.getString("facebook_id");
        String name = user.getString("name");

        NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification =
            new Notification(
                android.R.drawable.btn_default,
                "近くに" + name + "さんがいるようです。",
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        //	Notificationが選択された場合のIntent
        Intent intent = new Intent(Intent.ACTION_VIEW);
        PendingIntent contentIntent =
            PendingIntent.getActivity(LocationDetectService.this, 0, intent, 0);
        notification.setLatestEventInfo(
            getApplicationContext(), "Pecori", "近くに" + name + "さんがいるようです。", contentIntent);
        notificationManager.notify(R.string.app_name, notification);
      }
    }