Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#setParameter()

The following examples show how to use org.apache.commons.httpclient.methods.PostMethod#setParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSubmarineServerTest.java    From submarine with Apache License 2.0 6 votes vote down vote up
private static String getCookie(String user, String password) throws IOException {
  HttpClient httpClient = new HttpClient();
  PostMethod postMethod = new PostMethod(URL + "/login");
  postMethod.addRequestHeader("Origin", URL);
  postMethod.setParameter("password", password);
  postMethod.setParameter("userName", user);
  httpClient.executeMethod(postMethod);
  LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
  Pattern pattern = Pattern.compile("JSESSIONID=([a-zA-Z0-9-]*)");
  Header[] setCookieHeaders = postMethod.getResponseHeaders("Set-Cookie");
  String jsessionId = null;
  for (Header setCookie : setCookieHeaders) {
    java.util.regex.Matcher matcher = pattern.matcher(setCookie.toString());
    if (matcher.find()) {
      jsessionId = matcher.group(1);
    }
  }

  if (jsessionId != null) {
    return jsessionId;
  } else {
    return StringUtils.EMPTY;
  }
}
 
Example 2
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public String getAccessToken(String username, String password) {
	logger.debug("IN");
	try {
		PostMethod httppost = createPostMethodForAccessToken();
		httppost.setParameter("grant_type", "password");
		httppost.setParameter("username", username);
		httppost.setParameter("password", password);
		httppost.setParameter("client_id", config.getProperty("CLIENT_ID"));

		return sendHttpPost(httppost);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while trying to get access token from OAuth2 provider", e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 3
Source File: BusinessJob.java    From http4e with Apache License 2.0 6 votes vote down vote up
private void addParams( PostMethod postMethod, Map<String, String> parameterizedMap){
   for (Iterator it = model.getParameters().entrySet().iterator(); it.hasNext();) {
      Map.Entry me = (Map.Entry) it.next();
      String key = (String) me.getKey();
      List values = (List) me.getValue();
      StringBuilder sb = new StringBuilder();
      int cnt = 0;
      for (Iterator it2 = values.iterator(); it2.hasNext();) {
         String val = (String) it2.next();
         if (cnt != 0) {
            sb.append(",");
         }
         sb.append(val);
         cnt++;
      }

      String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);
      postMethod.setParameter(key, parameterizedVal);
   }
}
 
Example 4
Source File: JunkUtils.java    From http4e with Apache License 2.0 6 votes vote down vote up
public static String getHdToken(String url, String md){
      final HttpClient client = new HttpClient();      
      PostMethod post = new PostMethod(url);
      post.setRequestHeader("content-type", "application/x-www-form-urlencoded");
      post.setParameter("v", md);
      
      post.setApacheHttpListener(httpListener);
      try {
         HttpUtils.execute(client, post, responseReader);
         Header header = post.getResponseHeader("hd-token");
         if(header != null){
//            System.out.println("hd-token:" + header.getValue() + "'");
            return header.getValue();
         }
      } catch (Exception ignore) {
         ExceptionHandler.handle(ignore);
      } finally {
         if(post != null) post.releaseConnection();
      }
      return null;
   }
 
Example 5
Source File: AbstractTestRestApi.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private static String getCookie(String user, String password) throws IOException {
  HttpClient httpClient = new HttpClient();
  PostMethod postMethod = new PostMethod(URL + "/login");
  postMethod.addRequestHeader("Origin", URL);
  postMethod.setParameter("password", password);
  postMethod.setParameter("userName", user);
  httpClient.executeMethod(postMethod);
  LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
  Pattern pattern = Pattern.compile("JSESSIONID=([a-zA-Z0-9-]*)");
  Header[] setCookieHeaders = postMethod.getResponseHeaders("Set-Cookie");
  String jsessionId = null;
  for (Header setCookie : setCookieHeaders) {
    java.util.regex.Matcher matcher = pattern.matcher(setCookie.toString());
    if (matcher.find()) {
      jsessionId = matcher.group(1);
    }
  }

  if (jsessionId != null) {
    return jsessionId;
  } else {
    return StringUtils.EMPTY;
  }
}
 
Example 6
Source File: ZeppelinServerMock.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private static String getCookie(String user, String password) throws IOException {
  HttpClient httpClient = new HttpClient();
  PostMethod postMethod = new PostMethod(URL + "/login");
  postMethod.addRequestHeader("Origin", URL);
  postMethod.setParameter("password", password);
  postMethod.setParameter("userName", user);
  httpClient.executeMethod(postMethod);
  LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
  Pattern pattern = Pattern.compile("JSESSIONID=([a-zA-Z0-9-]*)");
  Header[] setCookieHeaders = postMethod.getResponseHeaders("Set-Cookie");
  String jsessionId = null;
  for (Header setCookie : setCookieHeaders) {
    java.util.regex.Matcher matcher = pattern.matcher(setCookie.toString());
    if (matcher.find()) {
      jsessionId = matcher.group(1);
    }
  }

  if (jsessionId != null) {
    return jsessionId;
  } else {
    return StringUtils.EMPTY;
  }
}
 
Example 7
Source File: OnlyHttpClient3Upload.java    From oim-fx with MIT License 5 votes vote down vote up
public String upload(String http, String tagName, File file, Map<String, String> dataMap) {
	String body = null;
	PostMethod filePost = new PostMethod(http);

	try {
		if (dataMap != null) {
			// 通过以下方法可以模拟页面参数提交
			// filePost.setParameter("name", "中文");
			Iterator<Map.Entry<String, String>> i = dataMap.entrySet().iterator();
			while (i.hasNext()) {
				Map.Entry<String, String> entry = i.next();
				String inputName = (String) entry.getKey();
				String inputValue = (String) entry.getValue();
				filePost.setParameter(inputName, inputValue);
			}
		}

		Part[] parts = { new FilePart(file.getName(), file) };
		filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		int status = client.executeMethod(filePost);
		body = filePost.getResponseBodyAsString();
		if (status == HttpStatus.SC_OK) {// 上传成功
		} else {// 上传失败
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		filePost.releaseConnection();
	}
	return body;
}
 
Example 8
Source File: HttpClientUtil.java    From Gather-Platform with GNU General Public License v3.0 5 votes vote down vote up
public String post(String postURL, Map<String, String> partam, String cookies)
            throws IOException {
//        clearCookies();
        PostMethod p = new PostMethod(postURL);
        for (String key : partam.keySet()) {
            if (partam.get(key) != null) {
                p.setParameter(key, partam.get(key));
            }
        }
        if (StringUtils.isNotEmpty(cookies)) {
            p.addRequestHeader("cookie", cookies);
        }
        hc.executeMethod(p);
        return p.getResponseBodyAsString();
    }
 
Example 9
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getAccessToken(String code) {
	logger.debug("IN");
	try {
		PostMethod httppost = createPostMethodForAccessToken();
		httppost.setParameter("grant_type", "authorization_code");
		httppost.setParameter("code", code);
		httppost.setParameter("redirect_uri", config.getProperty("REDIRECT_URI"));

		return sendHttpPost(httppost);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while trying to get access token from OAuth2 provider", e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 10
Source File: HttpClientUtil.java    From spider with GNU General Public License v3.0 5 votes vote down vote up
public String post(String postURL, Map<String, String> partam, String cookies)
            throws IOException {
//        clearCookies();
        PostMethod p = new PostMethod(postURL);
        for (String key : partam.keySet()) {
            if (partam.get(key) != null) {
                p.setParameter(key, partam.get(key));
            }
        }
        if (StringUtils.isNotEmpty(cookies)) {
            p.addRequestHeader("cookie", cookies);
        }
        hc.executeMethod(p);
        return p.getResponseBodyAsString();
    }
 
Example 11
Source File: ErrorReportSender.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
protected void addHttpPostParams(Map<String, String> values, PostMethod method) {
  for (String key : values.keySet()) {
    String parameterValue = values.get(key);
    parameterValue = parameterValue != null ? parameterValue : NULL;
    method.setParameter(key, parameterValue);
  }
}
 
Example 12
Source File: UrlEncordedFormPostViaProxyTestCase.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = {
        "wso2.esb" }, description = "Patch : ESBJAVA-1696 : Encoded Special characters in the URL is decoded at the Gateway and not re-encoded", enabled = true)
public void testEncodingSpecialCharacterViaHttpProxy() throws IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    client.getParams().setSoTimeout(5000);
    client.getParams().setConnectionManagerTimeout(5000);

    // Create POST method
    String url = getProxyServiceURLHttp("MyProxy");
    PostMethod method = new PostMethod(url);
    // Set parameters on POST
    String value1 = "Hello World";
    String value2 = "This is a Form Submission containing %";
    String value3 = URLEncoder.encode("This is an encoded value containing %");
    method.setParameter("test1", value1);
    method.addParameter("test2", value2);
    method.addParameter("test3", value3);

    // Execute and print response
    try {
        client.executeMethod(method);
    } catch (Exception e) {

    } finally {
        method.releaseConnection();
    }
    String response = wireMonitorServer.getCapturedMessage();
    String[] responseArray = response.split("test");

    if (responseArray.length < 3) {
        Assert.fail("All attributes are not sent");
    }
    for (String res : responseArray) {
        if (res.startsWith("1")) {
            Assert.assertTrue(res.startsWith("1=" + URLEncoder.encode(value1).replace("+", "%20")));
        } else if (res.startsWith("2")) {
            Assert.assertTrue(res.startsWith("2=" + URLEncoder.encode(value2).replace("+", "%20")));
        } else if (res.startsWith("3")) {
            Assert.assertTrue(res.startsWith("3=" + URLEncoder.encode(value3)));
        }
    }

}
 
Example 13
Source File: OnlyHttpClient3Upload.java    From oim-fx with MIT License 4 votes vote down vote up
public static String uploads(String http, String tagName, List<File> files, Map<String, String> dataMap) {
	String body = null;
	PostMethod filePost = new PostMethod(http);

	try {
		filePost.setRequestHeader("Content-Type", "application/octet-stream;charset=UTF-8");
		if (dataMap != null) {
			// 通过以下方法可以模拟页面参数提交
			// filePost.setParameter("name", "中文");
			Iterator<Map.Entry<String, String>> i = dataMap.entrySet().iterator();
			while (i.hasNext()) {
				Map.Entry<String, String> entry = i.next();
				String inputName = (String) entry.getKey();
				String inputValue = (String) entry.getValue();
				filePost.setParameter(inputName, inputValue);
			}
		}
		if (null != files && !files.isEmpty()) {
			int size = files.size();
			Part[] parts = new Part[size];
			for (int i = 0; i < size; i++) {
				File file = files.get(i);
				parts[i] = new FilePart(file.getName(), file);
			}
			filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
		}

		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		int status = client.executeMethod(filePost);
		body = filePost.getResponseBodyAsString();
		System.out.println(body);
		if (status == HttpStatus.SC_OK) {// 上传成功
		} else {// 上传失败
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		filePost.releaseConnection();
	}
	return body;
}
 
Example 14
Source File: UrlEncordedFormPostViaProxyTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
@Test(groups = {"wso2.esb"}, description = "Patch : ESBJAVA-1696 : Encoded Special characters in the URL is decoded at the Gateway and not re-encoded", enabled = true)
public void testEncodingSpecialCharacterViaHttpProxy() throws IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(
            HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
    client.getParams().setSoTimeout(5000);
    client.getParams().setConnectionManagerTimeout(5000);

    // Create POST method
    String url = getProxyServiceURLHttp("MyProxy");
    PostMethod method = new PostMethod(url);
    // Set parameters on POST
    String value1 = "Hello World";
    String value2 = "This is a Form Submission containing %";
    String value3 = URLEncoder.encode("This is an encoded value containing %");
    method.setParameter("test1", value1);
    method.addParameter("test2", value2);
    method.addParameter("test3", value3);


    // Execute and print response
    try {
        client.executeMethod(method);
    } catch (Exception e) {

    } finally {
        method.releaseConnection();
    }
    String response = wireMonitorServer.getCapturedMessage();
    String[] responseArray = response.split("test");

    if (responseArray.length < 3) {
        Assert.fail("All attributes are not sent");
    }
    for (String res : responseArray) {
        if (res.startsWith("1")) {
            Assert.assertTrue(res.startsWith("1=" + URLEncoder.encode(value1).replace("+", "%20")));
        } else if (res.startsWith("2")) {
            Assert.assertTrue(res.startsWith("2=" + URLEncoder.encode(value2).replace("+", "%20")));
        } else if (res.startsWith("3")) {
            Assert.assertTrue(res.startsWith("3=" + URLEncoder.encode(value3)));
        }
    }

}
 
Example 15
Source File: WebServicePostUDAF.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
// KAVITHA: we need to join the rows returned by the service call with
// the input dataset based on shared variables between the input and output columns

public Object terminate(AggregationBuffer arg0) throws HiveException {
	// TODO Auto-generated method stub
	List<Object[]> input = ((TableAggregator) arg0).data;
	
//	System.out.println("printing input");
//	WebServiceInterface.prettyPrint(input);

	// serialize the data as XML
	HttpClient client = new HttpClient();

	PostMethod method = new PostMethod(urlForService);
	method.setParameter("funcData", serialize(input));
	BufferedReader br = null;
	List<Object[]> result = null;

	try {
		int returnCode = client.executeMethod(method);
		
		if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
			System.err.println("The Post method is not implemented by this URI");
			// still consume the response body
			method.getResponseBodyAsString();
		} else {
			result = parseResponse(method.getResponseBodyAsStream(), resolver, xpathForRows, xPathForColumns);
		}
	} catch (Exception e) {
		e.printStackTrace();
		;
	} finally {
		method.releaseConnection();
		if (br != null)
			try {
				br.close();
			} catch (Exception fe) {
			}
	}
	result = join(input, result);
	return result;
}