public void runSimpleLoginLoadTest() {
    HttpClient httpClient = getHttpClient();

    // RequestEntity re = new StringRequestEntity(raw_body, "text/xml",
    // "UTF-16");

    try {

      PostMethod postMethod = new PostMethod(getAsvip() + "mas/login");
      postMethod.addParameters(getReqParams());
      int statuscode = httpClient.executeMethod(postMethod);
      byte[] responseBody = postMethod.getResponseBody();
      postMethod.releaseConnection();
      // System.out.println(statuscode + " LOGIN   RESPONSE  ---- "+ new String(responseBody));

      postMethod = new PostMethod(getAsvip() + "mas/logout");
      statuscode = httpClient.executeMethod(postMethod);
      responseBody = postMethod.getResponseBody();
      //	System.out.println(statuscode + "  LOGOUT  RESPONSE  ---- "+ new String(responseBody));
      postMethod.releaseConnection();

    } catch (HttpException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private String getEditorResponse(String urlpath, String encProcessSrc) {
    HttpClient httpclient = new HttpClient();

    PostMethod authMethod = new PostMethod(urlpath);
    NameValuePair[] data = {
      new NameValuePair("j_username", "admin"), new NameValuePair("j_password", "admin")
    };
    authMethod.setRequestBody(data);
    try {
      httpclient.executeMethod(authMethod);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      authMethod.releaseConnection();
    }

    PostMethod theMethod = new PostMethod(urlpath);
    theMethod.setParameter("processsource", encProcessSrc);
    StringBuffer sb = new StringBuffer();
    try {
      httpclient.executeMethod(theMethod);
      sb.append(theMethod.getResponseBodyAsString());
      return sb.toString();

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      theMethod.releaseConnection();
    }
  }
Esempio n. 3
0
  /**
   * 鍙栧緱ST
   *
   * @param server
   * @param ticketGrantingTicket
   * @param service
   */
  private static String getServiceTicket(
      final String server, final String ticketGrantingTicket, final String service) {
    if (ticketGrantingTicket == null) return null;

    final HttpClient client = new HttpClient();

    final PostMethod post = new PostMethod(server + "/" + ticketGrantingTicket);

    post.setRequestBody(new NameValuePair[] {new NameValuePair("service", service)});

    try {
      client.executeMethod(post);

      final String response = post.getResponseBodyAsString();

      switch (post.getStatusCode()) {
        case 200:
          return response;

        default:
          warning("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
          info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
          break;
      }
    } catch (final IOException e) {
      warning(e.getMessage());
    } finally {
      post.releaseConnection();
    }

    return null;
  }
Esempio n. 4
0
  private Entry addEntry(String endpointAddress) throws Exception {
    Entry e = createBookEntry(256, "AtomBook");
    StringWriter w = new StringWriter();
    e.writeTo(w);

    PostMethod post = new PostMethod(endpointAddress);
    post.setRequestEntity(new StringRequestEntity(w.toString(), "application/atom+xml", null));
    HttpClient httpclient = new HttpClient();

    String location = null;
    try {
      int result = httpclient.executeMethod(post);
      assertEquals(201, result);
      location = post.getResponseHeader("Location").getValue();
      InputStream ins = post.getResponseBodyAsStream();
      Document<Entry> entryDoc = abdera.getParser().parse(copyIn(ins));
      assertEquals(entryDoc.getRoot().toString(), e.toString());
    } finally {
      post.releaseConnection();
    }

    Entry entry = getEntry(location, null);
    assertEquals(location, entry.getBaseUri().toString());
    assertEquals("AtomBook", entry.getTitle());
    return entry;
  }
  // http post
  public static String httpPost(String url, String body) throws Exception {
    ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
    Protocol.registerProtocol("https", new Protocol("https", fcty, 443));

    PostMethod post = new PostMethod(url);

    post.setRequestBody(body); // 这里添加xml字符串

    // 指定请求内容的类型
    post.setRequestHeader("Content-type", "application/json; charset=utf-8");
    HttpClient httpclient = new HttpClient(); // 创建 HttpClient 的实例

    httpclient.executeMethod(post);
    String res = post.getResponseBodyAsString();

    logger.info(res);

    post.releaseConnection(); // 释放连接

    if (res.indexOf("40001") > -1) {
      getFreshAccessToken();
    }

    return res;
  }
  @Override
  public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox)
      throws IOException, ServiceException {
    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
      throw ServiceException.FAILURE("SHA-256 digest not found", e);
    }
    ByteUtil.PositionInputStream pin =
        new ByteUtil.PositionInputStream(new DigestInputStream(in, digest));

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(getPostUrl(mbox));
    try {
      HttpClientUtil.addInputStreamToHttpMethod(post, pin, actualSize, "application/octet-stream");
      int statusCode = HttpClientUtil.executeMethod(client, post);
      if (statusCode == HttpStatus.SC_OK
          || statusCode == HttpStatus.SC_CREATED
          || statusCode == HttpStatus.SC_NO_CONTENT) {
        return getLocator(
            post, ByteUtil.encodeFSSafeBase64(digest.digest()), pin.getPosition(), mbox);
      } else {
        throw ServiceException.FAILURE("error POSTing blob: " + post.getStatusText(), null);
      }
    } finally {
      post.releaseConnection();
    }
  }
Esempio n. 7
0
  @Action("SignModeCheck")
  public String signModeCheck() throws Exception {
    try {
      HttpClient client = new HttpClient();
      String url = "http://127.0.0.1:" + getServerPort() + "/service/";
      logger.debug("url: " + url);

      CommunicationVo requestVo = new CommunicationVo();
      requestVo.setTradeCode("000001");
      requestVo.putParam("signMode", this.signVo.getSignMode());
      requestVo.putParam("certDn", this.signVo.getCertDn());
      PostMethod postMethod = new PostMethod(url);
      postMethod.addParameter("json", requestVo.toJson());

      client.executeMethod(postMethod);

      String resp = postMethod.getResponseBodyAsString().trim();

      postMethod.releaseConnection();
      logger.info("resp: " + resp);

      CommunicationVo respVo = CommunicationVo.getInstancefromJson(resp);
      if (!"0000".equals(respVo.getStatus())) {
        throw new ServiceException(respVo.getMessage());
      }
      this.dwzResp.ajaxSuccessForward(respVo.getMessage());
      this.dwzResp.setAlertClose(Boolean.valueOf(false));
    } catch (Exception e) {
      logger.error(ExceptionUtils.getStackTrace(e));
      this.dwzResp.errorForward(e.getMessage());
      return "dwz";
    }
    return "dwz";
  }
Esempio n. 8
0
  private static boolean createRepo(
      final String scmUrl, final String password, final String repository) {
    HttpClient client = new HttpClient();
    String uri = scmUrl + API + "/projects";
    LOGGER.debug("Create Repo: {}", uri);
    PostMethod post = new PostMethod(uri);

    post.setParameter("name", repository);
    post.setParameter("private_token", password);
    try {
      int result = client.executeMethod(post);
      LOGGER.info("Return code: " + result);
      for (Header header : post.getResponseHeaders()) {
        LOGGER.info(header.toString().trim());
      }
      LOGGER.info(post.getResponseBodyAsString());
    } catch (HttpException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    } finally {
      post.releaseConnection();
    }
    return true;
  }
Esempio n. 9
0
  public static String getHttp(String url, Boolean all) throws HttpException, Exception {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        throw new HttpException("访问失败,错误原因:" + method.getStatusLine());
      }

      InputStream response = method.getResponseBodyAsStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(response, "UTF-8"));
      if (all) {
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = br.readLine()) != null) {
          sb.append(str);
          sb.append("\r\n");
        }

        return sb.toString();
      } else {
        return br.readLine();
      }
    } finally {
      method.releaseConnection();
    }
  }
Esempio n. 10
0
  public static String postXml(String url, String xml) {
    String txt = null;
    PostMethod post = new PostMethod(url); // 请求地址
    post.setRequestBody(xml); // 这里添加xml字符串

    // 指定请求内容的类型
    post.setRequestHeader("Content-type", "text/xml; charset=iso-8859-1");
    HttpClient httpclient = new HttpClient(); // 创建 HttpClient 的实例
    int result;
    try {
      result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result); // 返回200为成功
      System.out.println("Response body: ");

      BufferedReader reader =
          new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "ISO-8859-1"));
      String tmp = null;
      String htmlRet = "";
      while ((tmp = reader.readLine()) != null) {
        htmlRet += tmp + "\r\n";
      }
      txt = new String(htmlRet.getBytes("ISO-8859-1"), "UTF-8");
      System.out.println(txt);

      // txt = post.getResponseBodyAsString();
      // System.out.println(post.getResponseBodyAsString());// 返回的内容
      post.releaseConnection(); // 释放连接
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return txt;
  }
Esempio n. 11
0
  public String mediaCreate(File f, DCArray assets_names, DCObject meta) throws Exception {
    String upload_url = this.fileUpload();

    PostMethod filePost = null;
    try {
      filePost = new PostMethod(upload_url);

      Part[] parts = {new FilePart("file", f)};

      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      HttpClient client = new HttpClient();
      client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

      int status = client.executeMethod(filePost);
      if (status == HttpStatus.SC_OK) {
        ObjectMapper mapper = new ObjectMapper();
        DCObject json_response =
            DCObject.create(mapper.readValue(filePost.getResponseBodyAsString(), Map.class));
        return this.mediaCreate(json_response.pull("url"), assets_names, meta);
      } else {
        throw new DCException("Upload failed.");
      }
    } catch (Exception e) {
      throw new DCException("Upload failed: " + e.getMessage());
    } finally {
      if (filePost != null) {
        filePost.releaseConnection();
      }
    }
  }
Esempio n. 12
0
  public static String postRequest(String url, Map<String, String> parameters) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    if (MapUtils.isNotEmpty(parameters)) {
      NameValuePair[] pairs = new NameValuePair[parameters.size()];
      Iterator<Entry<String, String>> iterator = parameters.entrySet().iterator();
      int index = 0;
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
        pairs[index++] = new NameValuePair(entry.getKey(), entry.getValue());
      }
      method.setRequestBody(pairs);
    }

    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("post method fail.url={},status={}", url, statusCode);
        return "";
      }
      byte[] responseBody = method.getResponseBody();
      return new String(responseBody, "UTF-8");
    } catch (Exception e) {
      logger.error("url=" + url, e);
      return "";
    } finally {
      method.releaseConnection();
    }
  }
  public String jasperAuthen(String username, String password) throws HttpException, IOException {
    logger.info("Authenticate : Jasper Report Server");

    Header[] headers = null;
    String sessionCookie = "";

    this.httpClient = new HttpClient();
    PostMethod mPost = new PostMethod(restLoginUrl);

    Header mtHeader = new Header();
    mtHeader.setName("content-type");
    mtHeader.setValue("application/x-www-form-urlencoded");
    mtHeader.setName("accept");

    mPost.addParameter("j_username", username);
    mPost.addParameter("j_password", password);
    mPost.addRequestHeader(mtHeader);

    httpClient.executeMethod(mPost);

    headers = mPost.getResponseHeaders();
    mPost.releaseConnection();

    sessionCookie = headers[2].getValue();
    logger.debug("SessionCookie is {}", sessionCookie);

    return sessionCookie;
  }
Esempio n. 14
0
	public String refreshToken(String refresh_token){
		
		String response = null;
		
		String Client_id = AppConfig.APP_ID;
		String Client_secret = AppConfig.APP_SECRET;
		String Url = "https://graph.renren.com/oauth/token?"+
		    "grant_type=refresh_token&"+
		    "refresh_token="+refresh_token+"&"+
		    "client_id="+Client_id+"&"+
		    "client_secret="+Client_secret;
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod (Url);
		
		try{
			client.executeMethod(method);
			if(method.getStatusCode()== HttpStatus.SC_OK){
				response = method.getResponseBodyAsString();
			}
		}catch (IOException e) {
			// TODO: handle exception
			System.out.println("Exception happend when processing Http Post:"+Url+"\n"+e);
		}finally{
			method.releaseConnection();
		}
		System.out.println("[FeedStub : run]"+response);
		
		net.sf.json.JSONArray jsonarray = net.sf.json.JSONArray.fromObject(response);
		net.sf.json.JSONObject jsonobject = jsonarray.getJSONObject(0);
		
		return (String) jsonobject.get("access_token");
	}
  private static JSONObject open(String host, int port) throws Exception {
    JSONObject result;
    PostMethod method = new PostMethod(host + ":" + port + "/api/data/store.open");

    // client.getState().setCredentials(new AuthScope(null, repoHostPort, "authentication"), new
    // UsernamePasswordCredentials(memberId, memberPassword));

    // method.setDoAuthentication(true);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
      System.err.println("Method failed: " + method.getStatusLine());
    }

    Reader reader = new InputStreamReader(method.getResponseBodyAsStream());
    CharArrayWriter cdata = new CharArrayWriter();
    char buf[] = new char[BUFFER_SIZE];
    int ret;
    while ((ret = reader.read(buf, 0, BUFFER_SIZE)) != -1) cdata.write(buf, 0, ret);

    reader.close();

    result = JSONObject.fromString(cdata.toString());

    method.releaseConnection();

    if (result.has("error")) throw new GeneralException(result.getString("error"));

    return result;
  }
 /** Process the result got from data sources. */
 @Override
 public void processResult(Operation operation, Object resultObj, Map<String, Object> keyMap)
     throws BaseCollectionException {
   // TODO Auto-generated method stub
   _logger.info("Processing VNX Mount Query response: {}", resultObj);
   final PostMethod result = (PostMethod) resultObj;
   try {
     ResponsePacket responsePacket =
         (ResponsePacket) _unmarshaller.unmarshal(result.getResponseBodyAsStream());
     // Extract session information from the response header.
     Header[] headers = result.getResponseHeaders(VNXFileConstants.CELERRA_SESSION);
     if (null != headers && headers.length > 0) {
       keyMap.put(VNXFileConstants.CELERRA_SESSION, headers[0].getValue());
       _logger.info("Received celerra session info from the Server.");
     }
     if (null != responsePacket.getPacketFault()) {
       Status status = responsePacket.getPacketFault();
       processErrorStatus(status, keyMap);
     } else {
       List<Object> mountList = getQueryResponse(responsePacket);
       // process the mount list
       processMountList(mountList, keyMap);
       keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_SUCCESS);
     }
   } catch (final Exception ex) {
     _logger.error(
         "Exception occurred while processing the vnx fileShare response due to {}",
         ex.getMessage());
     keyMap.put(VNXFileConstants.FAULT_DESC, ex.getMessage());
     keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_FAILURE);
   } finally {
     result.releaseConnection();
   }
   return;
 }
Esempio n. 17
0
 public String getHtmlByParamAndCode(NameValuePair[] param, String code) {
   StringBuffer contentStr = new StringBuffer();
   PostMethod postMethod = null;
   init();
   try {
     postMethod = new PostMethod(this.getUrl());
     postMethod.setRequestBody(param);
     postMethod.setRequestHeader(
         "User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); // ä¯ÀÀÆ÷αÔì
     client.executeMethod(postMethod);
     InputStream in = postMethod.getResponseBodyAsStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(in, code), 1024);
     String line = "";
     while ((line = br.readLine()) != null) {
       contentStr.append(line);
     }
     if (br != null) {
       br.close();
       br = null;
     }
     if (in != null) {
       in.close();
       in = null;
     }
   } catch (Exception e) {
     e.printStackTrace();
     release();
   } finally {
     postMethod.releaseConnection();
   }
   return contentStr.toString();
 }
  /**
   * 发上服务器的文件
   *
   * @param file
   * @return
   */
  private String sendHttpRequest(File file) {
    String string = null;
    PostMethod filePost = new PostMethod(targetURL);
    try {
      Part[] parts = {
        new FilePart("userFile.file", targetFile), new StringPart(paramType, param, "utf-8")
      };
      HttpMethodParams params = filePost.getParams();
      params.setContentCharset("utf-8");
      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(50000);

      Log.v("filePost", filePost.toString());
      Log.v("param", param);
      Log.v("paramType", paramType);
      int status = httpClient.executeMethod(filePost);
      // TODO
      Log.v("status--->", status + "");

      InputStream in = filePost.getResponseBodyAsStream();
      byte[] readStream = readStream(in);
      string = new String(readStream);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      filePost.releaseConnection();
    }
    return string;
  }
Esempio n. 19
0
  /**
   * 执行一个HTTP POST 请求,返回请求响应的HTML
   *
   * @param url 请求的URL 地址
   * @param params 请求的查询参数,可以为null
   * @return 返回请求响应的HTML
   */
  private static String doPost(String url, Map<String, String> params) {
    String response = null;
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    // 设置Post 数据
    if (!params.isEmpty()) {
      int i = 0;
      NameValuePair[] data = new NameValuePair[params.size()];
      for (Entry<String, String> entry : params.entrySet()) {
        data[i] = new NameValuePair(entry.getKey(), entry.getValue());
        i++;
      }
      postMethod.setRequestBody(data);
    }
    try {

      client.executeMethod(postMethod);
      if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
        response = postMethod.getResponseBodyAsString();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      postMethod.releaseConnection();
    }
    return response;
  }
Esempio n. 20
0
 /*     */ public static byte[] post(String url, RequestEntity requestEntity)
     /*     */ throws Exception
       /*     */ {
   /*  96 */ PostMethod method = new PostMethod(url);
   /*  97 */ method.addRequestHeader("Connection", "Keep-Alive");
   /*  98 */ method.getParams().setCookiePolicy("ignoreCookies");
   /*  99 */ method
       .getParams()
       .setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));
   /* 100 */ method.setRequestEntity(requestEntity);
   /* 101 */ method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   /*     */ try
   /*     */ {
     /* 104 */ int statusCode = client.executeMethod(method);
     /* 105 */ if (statusCode != 200) {
       /* 106 */ return null;
       /*     */ }
     /* 108 */ return method.getResponseBody();
     /*     */ }
   /*     */ catch (SocketTimeoutException e) {
     /* 111 */ return null;
     /*     */ } catch (Exception e) {
     /* 113 */ return null;
     /*     */ } finally {
     /* 115 */ method.releaseConnection();
     /*     */ }
   /*     */ }
Esempio n. 21
0
  public String getContextByPostMethod(String url, List<KeyValue> params) {
    HttpClient client = getHttpClient();

    client.getParams().setParameter("http.protocol.content-charset", this.codeing);

    PostMethod post = null;
    String result = "";
    try {
      URL u = new URL(url);
      client
          .getHostConfiguration()
          .setHost(
              u.getHost(), u.getPort() == -1 ? u.getDefaultPort() : u.getPort(), u.getProtocol());

      post = new PostMethod(u.getPath());

      NameValuePair[] nvps = new NameValuePair[params.size()];
      int i = 0;
      for (KeyValue kv : params) {
        nvps[i] = new NameValuePair(kv.getKey(), kv.getValue());
        i++;
      }

      post.setRequestBody(nvps);

      client.executeMethod(post);
      result = post.getResponseBodyAsString();
    } catch (Exception e) {
      throw new NetException("HttpClient catch!", e);
    } finally {
      if (post != null) post.releaseConnection();
    }
    return result;
  }
Esempio n. 22
0
 public static String executePost(final String host, final String path, final List<Part> parts)
     throws Exception {
   final HttpClient client = new HttpClient();
   client.getParams().setParameter("http.protocol.single-cookie-header", true);
   client
       .getParams()
       .setParameter(
           "http.useragent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
   final HttpState httpState = new HttpState();
   final HostConfiguration hostConfiguration = new HostConfiguration();
   // add the proxy
   HttpProxy.addProxy(hostConfiguration);
   hostConfiguration.setHost(host);
   final MultipartRequestEntity entity =
       new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), new HttpMethodParams());
   final PostMethod post = new PostMethod(getHostUrlPrefix(host) + path);
   post.setRequestEntity(entity);
   try {
     final int status = client.executeMethod(hostConfiguration, post, httpState);
     if (status != 200) {
       throw new Exception(
           "Post command to " + host + " failed, the server returned status: " + status);
     }
     return post.getResponseBodyAsString();
   } finally {
     post.releaseConnection();
   }
 }
Esempio n. 23
0
 private void doPost(
     String realm,
     String host,
     String user,
     String pass,
     String url,
     boolean handshake,
     boolean preemtive,
     int result)
     throws Exception {
   HttpClient client = new HttpClient();
   client.getParams().setAuthenticationPreemptive(preemtive);
   client
       .getState()
       .setCredentials(
           new AuthScope(host, -1, realm), new UsernamePasswordCredentials(user, pass));
   PostMethod post = new PostMethod(url);
   post.setDoAuthentication(handshake);
   StringRequestEntity requestEntity = new StringRequestEntity(soapRequest, "text/xml", "UTF-8");
   post.setRequestEntity(requestEntity);
   try {
     int status = client.executeMethod(post);
     assertEquals(result, status);
     assertNotNull(post.getResponseBodyAsString());
   } finally {
     post.releaseConnection();
   }
 }
Esempio n. 24
0
  public static byte[] post(String url, RequestEntity requestEntity) throws Exception {

    PostMethod method = new PostMethod(url);
    method.addRequestHeader("Connection", "Keep-Alive");
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    method.setRequestEntity(requestEntity);
    method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("httpCode=" + statusCode);
        return method.getResponseBody();
      }
      return method.getResponseBody();

    } catch (SocketTimeoutException e) {
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      method.releaseConnection();
    }
  }
 @Test
 public void testSettingsCreateWithEmptyJson() throws IOException {
   // Call Create Setting REST API
   PostMethod post = httpPost("/interpreter/setting/", "");
   LOG.info("testSettingCRUD create response\n" + post.getResponseBodyAsString());
   assertThat("test create method:", post, isBadRequest());
   post.releaseConnection();
 }
Esempio n. 26
0
  public Response multPartURL(
      String url, PostParameter[] params, ImageItem item, boolean authenticated)
      throws WeiboException {
    PostMethod post = new PostMethod(url);
    try {
      org.apache.commons.httpclient.HttpClient client = getHttpClient();
      long t = System.currentTimeMillis();
      Part[] parts = null;
      if (params == null) {
        parts = new Part[1];
      } else {
        parts = new Part[params.length + 1];
      }
      if (params != null) {
        int i = 0;
        for (PostParameter entry : params) {
          parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
        }
        parts[parts.length - 1] =
            new ByteArrayPart(item.getContent(), item.getName(), item.getContentType());
      }
      post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
      List<Header> headers = new ArrayList<Header>();

      if (authenticated) {
        if (oauth == null) {}
        String authorization = null;
        if (null != oauth) {
          // use OAuth
          authorization = oauth.generateAuthorizationHeader("POST", url, params, oauthToken);
        } else {
          throw new IllegalStateException(
              "Neither user ID/password combination nor OAuth consumer key/secret combination supplied");
        }
        headers.add(new Header("Authorization", authorization));
        log("Authorization: " + authorization);
      }
      client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
      client.executeMethod(post);

      Response response = new Response();
      response.setResponseAsString(post.getResponseBodyAsString());
      response.setStatusCode(post.getStatusCode());

      log(
          "multPartURL URL:"
              + url
              + ", result:"
              + response
              + ", time:"
              + (System.currentTimeMillis() - t));
      return response;
    } catch (Exception ex) {
      throw new WeiboException(ex.getMessage(), ex, -1);
    } finally {
      post.releaseConnection();
    }
  }
Esempio n. 27
0
  public static void main(String[] args) {
    // (1)构造HttpClient的实例
    HttpClient httpClient = new HttpClient();

    // (2)创建POST方法的实例
    PostMethod postMethod =
        new PostMethod("http://10.3.75.203:9080/ESB/appleServie?serviceCode=authentication");
    //		 GetMethod getMethod = new GetMethod("http://*****:*****@apple.com\",\"password\": \"Apple1234\", \"shipTo\":\"863348\",\"langCode\":\"en\",\"timeZone\":\"420\"}";
    postMethod.setRequestHeader("http.default-headers", authenticateText);
    // 使用系统提供的默认的恢复策略
    postMethod
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
      postMethod.setRequestEntity(
          new StringRequestEntity(authenticateText, "text/xml; charset=UTF-8", "UTF-8"));
      // (4)执行postMethod
      int statusCode = httpClient.executeMethod(postMethod);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + postMethod.getStatusLine());
      }

      // (5)读取response头信息
      //			Header headerResponse = postMethod
      //					.getResponseHeader("response_key");
      //			String headerStr = headerResponse.getValue();
      // (6)读取内容
      byte[] responseBody = postMethod.getResponseBody();
      // (7) 处理内容
      //			System.out.println(headerStr);
      System.out.println("返回的内容信息:" + new String(responseBody, "UTF-8"));
    } catch (HttpException e) {
      // 发生致命的异常,可能是协议不对或者返回的内容有问题
      System.out.println("Please check your provided http address!");
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 释放连接
      postMethod.releaseConnection();
    }
  }
Esempio n. 28
0
 protected void doAuthorization(
     HttpClient httpclient, HttpMethod method, Map<String, Object> params) {
   if (type == null) {
     return;
   }
   String u = (String) params.get("Username");
   String p = (String) params.get("Password");
   if (u == null || p == null) {
     u = this.username;
     p = this.password;
   }
   if (u == null) {
     throw new IllegalArgumentException("Could not find username");
   }
   if (p == null) {
     throw new IllegalArgumentException("Could not find password");
   }
   if (type == AuthenticationType.BASIC) {
     httpclient
         .getState()
         .setCredentials(
             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
             new UsernamePasswordCredentials(u, p));
     method.setDoAuthentication(true);
   } else if (type == AuthenticationType.FORM_BASED) {
     String authUrlStr = (String) params.get("AuthUrl");
     if (authUrlStr == null) {
       authUrlStr = authUrl;
     }
     if (authUrlStr == null) {
       throw new IllegalArgumentException("Could not find authentication url");
     }
     try {
       httpclient.executeMethod(method);
     } catch (IOException e) {
       throw new RuntimeException("Could not execute request for form-based authentication", e);
     } finally {
       method.releaseConnection();
     }
     PostMethod authMethod = new PostMethod(authUrlStr);
     NameValuePair[] data = {
       new NameValuePair("j_username", u), new NameValuePair("j_password", p)
     };
     authMethod.setRequestBody(data);
     try {
       httpclient.executeMethod(authMethod);
     } catch (IOException e) {
       throw new RuntimeException("Could not initialize form-based authentication", e);
     } finally {
       authMethod.releaseConnection();
     }
   } else {
     throw new RuntimeException("Unknown AuthenticationType " + type);
   }
 }
Esempio n. 29
0
  @Override
  public long setTargetVersion(PublishingTargetItem target, long newVersion, String site) {
    long resoponseVersion = -1;
    if (target.getVersionUrl() != null && !target.getVersionUrl().isEmpty()) {
      LOGGER.debug("Set deployment agent version for target {0}", target.getName());
      URL versionUrl = null;
      try {
        versionUrl = new URL(target.getVersionUrl());
      } catch (MalformedURLException e) {
        LOGGER.error("Invalid set version URL for target [%s]", target.getName());
        return resoponseVersion;
      }
      PostMethod postMethod = null;
      HttpClient client = null;
      try {
        postMethod = new PostMethod(target.getVersionUrl());
        postMethod.addParameter(TARGET_REQUEST_PARAMETER, target.getTarget());
        postMethod.addParameter(VERSION_REQUEST_PARAMETER, String.valueOf(newVersion));
        String siteId = target.getSiteId();
        if (StringUtils.isEmpty(siteId)) {
          siteId = site;
        }
        postMethod.addParameter(SITE_REQUEST_PARAMETER, site);
        client = new HttpClient();
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
          String responseText = postMethod.getResponseBodyAsString();
          if (responseText != null && !responseText.isEmpty()) {
            resoponseVersion = Long.parseLong(responseText);
          } else {
            resoponseVersion = 0;
          }
        }

      } catch (Exception e) {
        LOGGER.error(
            "Target {0} responded with error while setting target version. Set version failed for url {1}",
            target.getName(), target.getVersionUrl());

      } finally {
        if (client != null) {
          HttpConnectionManager mgr = client.getHttpConnectionManager();
          if (mgr instanceof SimpleHttpConnectionManager) {
            ((SimpleHttpConnectionManager) mgr).shutdown();
          }
        }
        if (postMethod != null) {
          postMethod.releaseConnection();
        }
        postMethod = null;
        client = null;
      }
    }
    return resoponseVersion;
  }
  @Override
  public void processResult(Operation operation, Object resultObj, Map<String, Object> keyMap)
      throws BaseCollectionException {
    _logger.info("processing snapshot id response" + resultObj);
    final PostMethod result = (PostMethod) resultObj;
    try {
      ResponsePacket responsePacket =
          (ResponsePacket) _unmarshaller.unmarshal(result.getResponseBodyAsStream());
      Status status = null;
      if (null != responsePacket.getPacketFault()) {
        status = responsePacket.getPacketFault();
        processErrorStatus(status, keyMap);
      } else {

        List<Object> snapshotList = getQueryResponse(responsePacket);
        List<Checkpoint> snapsList = new ArrayList<Checkpoint>();

        final String fsId = (String) keyMap.get(VNXFileConstants.FILESYSTEM_ID);
        _logger.info("Looking for all snapshots of filesystem {}", fsId);

        Iterator<Object> snapshotItr = snapshotList.iterator();
        if (snapshotItr.hasNext()) {
          status = (Status) snapshotItr.next();
          if (status.getMaxSeverity() == Severity.OK) {
            while (snapshotItr.hasNext()) {
              Checkpoint point = (Checkpoint) snapshotItr.next();
              _logger.debug(
                  "searching snapshot: {} - {}", point.getName(), point.getCheckpointOf());
              if (point.getCheckpointOf().equalsIgnoreCase(fsId)) {
                String id = point.getCheckpoint();
                String localFSId = point.getCheckpointOf();
                _logger.info("Found matching snapshot: {} and checkpoint of {}", id, localFSId);
                snapsList.add(point);
              }
            }
            _logger.info("Number of Snapshots found for FS : {} are : {}", fsId, snapsList.size());
            keyMap.put(VNXFileConstants.SNAPSHOTS_LIST, snapsList);
            keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_SUCCESS);
          } else {
            _logger.error("Error in getting the snapshot information.");
            processErrorStatus(status, keyMap);
          }
        }
      }

    } catch (final Exception ex) {
      _logger.error(
          "Exception occurred while processing the snapshot response due to {}", ex.getMessage());
      keyMap.put(VNXFileConstants.FAULT_DESC, ex.getMessage());
      keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_FAILURE);
    } finally {
      result.releaseConnection();
    }
  }