Java Code Examples for org.apache.commons.httpclient.methods.PostMethod

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project integration-tests, under directory /picketlink-trust-tests/src/test/java/org/picketlink/test/trust/tests/.

Source file: ServletToWSTestCase.java

  23 
vote

@Test public void testServlet2WS() throws Exception {
  HttpClient client=new HttpClient();
  PostMethod post=new PostMethod("http://localhost:8080/binary-test/TestWSInvokingServlet");
  post.addRequestHeader("TEST_HEADER","somevalue");
  int result=client.executeMethod(post);
  assertEquals(200,result);
}
 

Example 2

From project jBilling, under directory /src/java/com/sapienter/jbilling/server/payment/tasks/.

Source file: PaymentSageTask.java

  23 
vote

/** 
 * Make request to agteway
 * @return response from gateway
 */
private String makeCall(NVPList request,boolean isAch) throws IOException {
  LOG.debug("Request to " + PROCESSOR + " gateway sending...");
  HttpClient client=new HttpClient();
  client.setConnectionTimeout(getTimeoutSeconds() * 1000);
  PostMethod post=new PostMethod(getUrl(isAch));
  post.setRequestBody(request.toArray());
  client.executeMethod(post);
  String responseBody=post.getResponseBodyAsString();
  LOG.debug("Got response:" + responseBody);
  post.releaseConnection();
  post.recycle();
  return responseBody;
}
 

Example 3

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-client/src/main/java/com/utest/webservice/client/rest/.

Source file: RestClient.java

  22 
vote

public HttpMethod createPost(String service,String path,Map<String,Object> parameters){
  final PostMethod post=new PostMethod(baseUrl + servicePath + service+ "/"+ path);
  post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,true);
  for (  final Map.Entry<String,Object> param : parameters.entrySet()) {
    post.addParameter(param.getKey(),(param.getValue() == null) ? "" : param.getValue().toString());
  }
  setHeader(post);
  return post;
}
 

Example 4

From project data-access, under directory /src/org/pentaho/platform/dataaccess/client/.

Source file: ConnectionServiceClient.java

  22 
vote

/** 
 * Adds a connection to the server's configuration. Returns true if the attempt was successful. setHost(), setUserId() and setPassword() must be called before this method is called.
 * @param connection The connection to be added
 * @return True if the addition was successful
 */
public boolean addConnection(Connection connection) throws ConnectionServiceException {
  String xml=getConnectionXml(connection);
  PostMethod callMethod=new PostMethod(serviceUrl + "/addConnection");
  RequestEntity requestEntity=new StringRequestEntity(xml);
  callMethod.setRequestEntity(requestEntity);
  Node node=getResultNode(callMethod);
  return node != null && Boolean.parseBoolean(this.getNodeText(node));
}
 

Example 5

From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/model/util/.

Source file: RESTFacade.java

  22 
vote

/** 
 * Update method that explicitly limits the updates to parameter value changes
 * @param fHandle
 * @param parameterUpdates
 * @return
 * @throws PasserelleException
 */
public FlowHandle updateRemoteFlow(FlowHandle fHandle,Map<String,String> parameterUpdates) throws PasserelleException {
  String updateURL=fHandle.getAuthorativeResourceLocation().toString() + "/update";
  PostMethod updateMethod=new PostMethod(updateURL);
  for (  Entry<String,String> paramUpdateEntry : parameterUpdates.entrySet()) {
    updateMethod.setParameter(paramUpdateEntry.getKey(),paramUpdateEntry.getValue());
  }
  String seqDetailResponse=invokeMethodForURL(updateMethod);
  FlowHandle updatedFlowHandle=buildFlowHandle(seqDetailResponse);
  return updatedFlowHandle;
}
 

Example 6

From project eclipse-instasearch, under directory /instasearch/src/it/unibz/instasearch/ui/.

Source file: ReportErrorDialog.java

  22 
vote

/** 
 * @throws IOException 
 * @throws HttpException 
 */
private void reportError() throws HttpException, IOException {
  HttpClient httpClient=new HttpClient();
  PostMethod postMethod=new PostMethod(InstaSearchPlugin.getErrorReportURL());
  postMethod.addParameter("subj",message);
  postMethod.addParameter("attn","Exception");
  postMethod.addParameter("notes",getStatusContent(status));
  postMethod.addParameter("visitor","InstaSearch Plugin " + InstaSearchPlugin.getVersion());
  httpClient.executeMethod(postMethod);
  postMethod.releaseConnection();
}
 

Example 7

From project ereviewboard, under directory /org.review_board.ereviewboard.core/src/org/review_board/ereviewboard/core/client/.

Source file: ReviewboardHttpClient.java

  22 
vote

public String executePost(String url,Map<String,String> parameters,IProgressMonitor monitor) throws ReviewboardException {
  PostMethod postRequest=new PostMethod(stripSlash(location.getUrl()) + url);
  postRequest.getParams().setParameter("Set-Cookie",getCookie(monitor));
  for (  String key : parameters.keySet()) {
    postRequest.setParameter(key,parameters.get(key));
  }
  return executeMethod(postRequest,monitor);
}
 

Example 8

From project Foglyn, under directory /com.foglyn.fogbugz/src/com/foglyn/fogbugz/.

Source file: Request.java

  22 
vote

Document post(String url,List<Part> parts,IProgressMonitor monitor) throws FogBugzException {
  PostMethod postMethod=new PostMethod(url);
  postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]),postMethod.getParams()));
  Document result=request(url,postMethod,monitor,new DocumentResponseProcessor());
  if (checkResponseError) {
    throwExceptionOnError(result);
  }
  return result;
}
 

Example 9

From project jentrata-msh, under directory /Clients/Corvus.WSClient/src/test/java/hk/hku/cecid/corvus/http/.

Source file: HttpSenderUnitTest.java

  22 
vote

/** 
 * Test whether the HTTP sender able to send the HTTP header with POST parameter to our monitor successfully. 
 */
public void testSendWithParameter() throws Exception {
  this.target=new HttpSender(this.testClassLogger,new KVPairData(0)){
    public HttpMethod onCreateRequest() throws Exception {
      PostMethod method=new PostMethod("http://localhost:1999");
      method.addParameter("testparamName","testparamValue");
      return method;
    }
  }
;
  this.assertSend();
}
 

Example 10

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/client/.

Source file: Client.java

  22 
vote

public void addCustomerInfo(String name,String password) throws Exception {
  System.out.println("HTTP POST to add customer info, user : " + name + ", password : "+ password);
  PostMethod post=new PostMethod("http://localhost:9002/customerservice/customers");
  setMethodHeaders(post,name,password);
  RequestEntity entity=new InputStreamRequestEntity(this.getClass().getClassLoader().getResourceAsStream("add_customer.xml"));
  post.setRequestEntity(entity);
  handleHttpMethod(post);
}
 

Example 11

From project mylyn.incubator, under directory /org.eclipse.mylyn.sandbox.tests/src/org/eclipse/mylyn/tasks/tests/web/.

Source file: WebRepositoryConnectorTest.java

  22 
vote

public void testEncodingParameters() throws Exception {
  TaskRepository repository=new TaskRepository(WebRepositoryConnector.REPOSITORY_TYPE,"http://foo.net");
  repository.setAuthenticationCredentials("USER","PASSWORD");
  repository.setProperty(WebRepositoryConnector.PROPERTY_LOGIN_REQUEST_METHOD,WebRepositoryConnector.REQUEST_POST);
  repository.setProperty(WebRepositoryConnector.PROPERTY_LOGIN_REQUEST_URL,"${serverUrl}/Login.php?xajax=xCheckUserLogin&xajaxargs[]=<xjxquery><q>${xjxquery}</q></xjxquery>");
  repository.setProperty("param_xjxquery","TestUserName=${userId}&TestUserPWD=${password}&HttpRefer=");
  Map<String,String> params=new HashMap<String,String>();
  PostMethod method=(PostMethod)WebRepositoryConnector.getLoginMethod(params,repository);
  String form=EncodingUtil.formUrlEncode(method.getParameters(),method.getRequestCharSet());
  assertEquals("xajax=xCheckUserLogin&" + "xajaxargs%5B%5D=%3Cxjxquery%3E%3Cq%3E" + "TestUserName%3DUSER%26"+ "TestUserPWD%3DPASSWORD%26"+ "HttpRefer%3D"+ "%3C%2Fq%3E%3C%2Fxjxquery%3E",form);
}
 

Example 12

From project pegadi, under directory /client/src/main/java/org/pegadi/client/.

Source file: ApplicationLauncher.java

  22 
vote

public boolean webLogin(String url,String user,String pass){
  log.info("Weblogin with url {}",url);
  PostMethod post=new PostMethod(url + "j_security_check");
  post.addParameter(new NameValuePair("j_username",user));
  post.addParameter(new NameValuePair("j_password",pass));
  try {
    LoginContext.httpClient.executeMethod(post);
  }
 catch (  IOException e) {
    log.error("Error executing method for weblogin",e);
    return false;
  }
  return true;
}
 

Example 13

From project picketlink-integration-tests, under directory /unit-tests/trust/src/test/java/org/picketlink/test/trust/tests/.

Source file: ServletToWSTestCase.java

  22 
vote

@Test public void testServlet2WS() throws Exception {
  HttpClient client=new HttpClient();
  PostMethod post=new PostMethod(TestUtil.getTargetURL("/binary-test/TestWSInvokingServlet"));
  post.addRequestHeader("TEST_HEADER","somevalue");
  int result=client.executeMethod(post);
  assertEquals(200,result);
}
 

Example 14

From project Red5, under directory /src/org/red5/server/net/rtmpt/.

Source file: RTMPTClientConnector.java

  22 
vote

private void finalizeConnection() throws IOException {
  log.debug("Sending close post");
  PostMethod closePost=new PostMethod(makeUrl("close"));
  closePost.setRequestEntity(ZERO_REQUEST_ENTITY);
  httpClient.executeMethod(closePost);
  closePost.getResponseBody();
}
 

Example 15

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/server/net/rtmpt/.

Source file: RTMPTClientConnector.java

  22 
vote

private void finalizeConnection() throws IOException {
  log.debug("Sending close post");
  PostMethod closePost=new PostMethod(makeUrl("close"));
  closePost.setRequestEntity(ZERO_REQUEST_ENTITY);
  httpClient.executeMethod(closePost);
  closePost.getResponseBody();
}
 

Example 16

From project searchable, under directory /src/main/java/net/mojodna/searchable/solr/.

Source file: SolrIndexer.java

  22 
vote

/** 
 * Commit pending documents to the index.
 * @throws IOException
 */
protected void commit() throws IOException {
  final PostMethod post=new PostMethod(solrPath);
  post.setRequestEntity(new StringRequestEntity("<commit waitFlush=\"false\" waitSearcher=\"false\"/>","text/xml","UTF-8"));
  log.debug("Committing.");
  getHttpClient().executeMethod(post);
}
 

Example 17

From project SeavusJB3, under directory /src/java/com/sapienter/jbilling/server/payment/tasks/.

Source file: PaymentSageTask.java

  22 
vote

/** 
 * Make request to agteway
 * @return response from gateway
 */
private String makeCall(NVPList request,boolean isAch) throws IOException {
  LOG.debug("Request to " + PROCESSOR + " gateway sending...");
  HttpClient client=new HttpClient();
  client.setConnectionTimeout(getTimeoutSeconds() * 1000);
  PostMethod post=new PostMethod(getUrl(isAch));
  post.setRequestBody(request.toArray());
  client.executeMethod(post);
  String responseBody=post.getResponseBodyAsString();
  LOG.debug("Got response:" + responseBody);
  post.releaseConnection();
  post.recycle();
  return responseBody;
}
 

Example 18

From project security, under directory /testsuite/src/test/java/org/jboss/seam/security/test/server/identity/.

Source file: LogoutTest.java

  22 
vote

/** 
 * Test for SEAMSECURITY-83
 */
@Test public void assertLogoutInvalidatesSession(@ArquillianResource(LogoutServlet.class) URL baseUrl) throws IOException {
  final HttpClient client=new HttpClient();
  final PostMethod put=new PostMethod(baseUrl.toString() + "logout");
  client.executeMethod(put);
  assertThat(put.getResponseBodyAsString(),is("loggedIn"));
  final DeleteMethod delete=new DeleteMethod(baseUrl.toString() + "logout");
  client.executeMethod(delete);
  assertThat(delete.getResponseBodyAsString(),is("loggedOut and session invalidated"));
}
 

Example 19

From project security_2, under directory /web-nutsNbolts/src/main/java/org/intalio/tempo/web/controller/.

Source file: LoginController.java

  22 
vote

public void sendUserAndRolesToPopulateCache(User user,String serverUrl){
  String url=serverUrl + "/gi/populaterolescache";
  String userName=user.getName();
  String[] userRoles=user.getRoles();
  String userRolesAsString=arrayToString(userRoles,",");
  PostMethod post=new PostMethod(url);
  post.addParameter("username",userName);
  post.addParameter("roles",userRolesAsString);
  LOG.debug("Sending post request to: " + url);
  executePost(post);
}
 

Example 20

From project signpost, under directory /signpost-commonshttp3/src/main/java/oauth/signpost/commonshttp3/.

Source file: Http3RequestAdapter.java

  22 
vote

public String getContentType(){
  String type=null;
  if (httpMethod instanceof PostMethod) {
    PostMethod postMethod=(PostMethod)httpMethod;
    type=postMethod.getRequestEntity().getContentType();
  }
 else {
    Header header=httpMethod.getRequestHeader("Content-Type");
    type=(header == null) ? null : header.getValue();
  }
  return type;
}
 

Example 21

From project Solbase-Solr, under directory /src/java/org/apache/solr/handler/.

Source file: SnapPuller.java

  22 
vote

/** 
 * Gets the latest commit version and generation from the master
 */
@SuppressWarnings("unchecked") NamedList getLatestVersion() throws IOException {
  PostMethod post=new PostMethod(masterUrl);
  post.addParameter(COMMAND,CMD_INDEX_VERSION);
  post.addParameter("wt","javabin");
  return getNamedListResponse(post);
}
 

Example 22

From project tempo, under directory /tas-service/src/main/java/org/intalio/tempo/workflow/tas/nuxeo/.

Source file: NuxeoStorageStrategy.java

  22 
vote

/** 
 * Upload the binary content of the file to nuxeo
 */
private void uploadFile(String uri,InputStream payload) throws IOException {
  PostMethod method=new PostMethod(uri);
  method.setRequestEntity(new InputStreamRequestEntity(payload));
  httpclient.executeMethod(method);
  method.releaseConnection();
}
 

Example 23

From project wayback, under directory /wayback-core/src/main/java/org/archive/wayback/resourcestore/locationdb/.

Source file: RemoteResourceFileLocationDB.java

  22 
vote

private void doPostMethod(final String operation,final String arcName,final String arcUrl) throws IOException {
  PostMethod method=new PostMethod(serverUrl);
  NameValuePair[] data={new NameValuePair(ResourceFileLocationDBServlet.OPERATION_ARGUMENT,operation),new NameValuePair(ResourceFileLocationDBServlet.NAME_ARGUMENT,arcName),new NameValuePair(ResourceFileLocationDBServlet.URL_ARGUMENT,arcUrl)};
  method.setRequestBody(data);
  int statusCode=client.executeMethod(method);
  if (statusCode != HttpStatus.SC_OK) {
    throw new IOException("Method failed: " + method.getStatusLine());
  }
  String responseString=method.getResponseBodyAsString();
  if (!responseString.startsWith(OK_RESPONSE_PREFIX)) {
    throw new IOException(responseString);
  }
}
 

Example 24

From project wissl, under directory /src/test/java/fr/msch/wissl/server/.

Source file: TServer.java

  22 
vote

protected String addUser(String username,String password,String auth,String sessionId) throws IOException {
  HttpClient c=new HttpClient();
  PostMethod m=new PostMethod(URL + "user/add");
  m.addParameter("username",username);
  m.addParameter("password",password);
  m.addParameter("auth",auth);
  if (sessionId != null) {
    m.addRequestHeader("sessionId",sessionId);
  }
  c.executeMethod(m);
  String ret=m.getResponseBodyAsString();
  return ret;
}
 

Example 25

From project xwiki-enterprise, under directory /xwiki-enterprise-test/xwiki-enterprise-test-rest/src/test/it/org/xwiki/test/rest/.

Source file: CommentsResourceTest.java

  22 
vote

@Test public void testPOSTCommentWithTextPlain() throws Exception {
  String commentsUri=getUriBuilder(CommentsResource.class).build(getWiki(),SPACE_NAME,PAGE_NAME).toString();
  GetMethod getMethod=executeGet(commentsUri);
  Assert.assertEquals(getHttpMethodInfo(getMethod),HttpStatus.SC_OK,getMethod.getStatusCode());
  Comments comments=(Comments)unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());
  int numberOfComments=comments.getComments().size();
  PostMethod postMethod=executePost(commentsUri,"Comment",MediaType.TEXT_PLAIN,"Admin","admin");
  Assert.assertEquals(getHttpMethodInfo(postMethod),HttpStatus.SC_CREATED,postMethod.getStatusCode());
  getMethod=executeGet(commentsUri);
  Assert.assertEquals(getHttpMethodInfo(getMethod),HttpStatus.SC_OK,getMethod.getStatusCode());
  comments=(Comments)unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());
  Assert.assertEquals(numberOfComments + 1,comments.getComments().size());
}
 

Example 26

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  21 
vote

protected int executeFormConfigUpload(String formConfig){
  HttpState state=new HttpState();
  state.setCredentials(new AuthScope(null,AuthScope.ANY_PORT),new UsernamePasswordCredentials(cmisUser,cmisPassword));
  LOGGER.info("Deploying form config XML: ");
  prettyLogXml(formConfig);
  PostMethod postMethod=new PostMethod(FORM_CONFIG_UPLOAD_URL);
  try {
    postMethod.setRequestEntity(new StringRequestEntity(formConfig,"application/xml","UTF-8"));
    HttpClient httpClient=new HttpClient();
    int result=httpClient.executeMethod(null,postMethod,state);
    LOGGER.info("Response status code: " + result);
    LOGGER.info("Response body: ");
    LOGGER.info(postMethod.getResponseBodyAsString());
    return result;
  }
 catch (  Throwable t) {
    System.err.println("Error: " + t.getMessage());
    t.printStackTrace();
  }
 finally {
    postMethod.releaseConnection();
  }
  throw new RuntimeException("Programmatic error. You shouldn't be here.");
}
 

Example 27

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHTTPClient.java

  21 
vote

public void post(String url,Header[] headers,NameValuePair[] params,RequestEntity requestEntity,AGResponseHandler handler) throws AGHttpException {
  PostMethod post=new PostMethod(url);
  setDoAuthentication(post);
  for (  Header header : headers) {
    post.addRequestHeader(header);
  }
  post.addRequestHeader("Accept-encoding","gzip");
  post.setQueryString(params);
  if (requestEntity != null) {
    post.setRequestEntity(requestEntity);
  }
  try {
    int httpCode=getHttpClient().executeMethod(post);
    if (httpCode == HttpURLConnection.HTTP_OK) {
      if (handler != null)       handler.handleResponse(post);
    }
 else     if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
      throw new AGHttpException(new UnauthorizedException());
    }
 else     if (!is2xx(httpCode)) {
      AGErrorHandler errHandler=new AGErrorHandler();
      errHandler.handleResponse(post);
      throw errHandler.getResult();
    }
  }
 catch (  HttpException e) {
    throw new AGHttpException(e);
  }
catch (  IOException e) {
    handleSessionConnectionError(e,url);
  }
 finally {
    if (handler == null || handler.releaseConnection()) {
      releaseConnection(post);
    }
  }
}
 

Example 28

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/deploy/activebpel/.

Source file: ActiveBPELDeployer.java

  21 
vote

/** 
 * @param re SOAP request entity to be sent to ActiveBPEL.
 * @return Response from the ActiveBPEL administration service.
 * @throws IOException
 */
private static RequestResult sendRequestToActiveBPEL(final String url,RequestEntity re) throws IOException {
  PostMethod method=null;
  try {
    HttpClient client=new HttpClient(new NoPersistenceConnectionManager());
    method=new PostMethod(url);
    method.setRequestEntity(re);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(1,false));
    method.addRequestHeader("SOAPAction","");
    client.executeMethod(method);
    RequestResult result=new RequestResult();
    result.setStatusCode(method.getStatusCode());
    result.setResponseBody(method.getResponseBodyAsString());
    return result;
  }
  finally {
    if (method != null) {
      method.releaseConnection();
    }
  }
}
 

Example 29

From project Carolina-Digital-Repository, under directory /access/src/main/java/edu/unc/lib/dl/ui/util/.

Source file: CDRTagLibUtil.java

  21 
vote

public static String postImport(HttpServletRequest request,String url){
  Map<String,String[]> parameters=request.getParameterMap();
  HttpClientParams params=new HttpClientParams();
  params.setContentCharset("UTF-8");
  HttpClient client=new HttpClient();
  client.setParams(params);
  PostMethod post=new PostMethod(url);
  Iterator<Entry<String,String[]>> parameterIt=parameters.entrySet().iterator();
  while (parameterIt.hasNext()) {
    Entry<String,String[]> parameter=parameterIt.next();
    for (    String parameterValue : parameter.getValue()) {
      post.addParameter(parameter.getKey(),parameterValue);
    }
  }
  try {
    client.executeMethod(post);
    return post.getResponseBodyAsString();
  }
 catch (  Exception e) {
    throw new ResourceNotFoundException("Failed to retrieve POST import request for " + url,e);
  }
 finally {
    post.releaseConnection();
  }
}
 

Example 30

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/api/.

Source file: BeesClientBase.java

  21 
vote

protected String executeUpload(String uploadURL,Map<String,String> params,Map<String,File> files,UploadProgress writeListener) throws Exception {
  HashMap<String,String> clientParams=getDefaultParameters();
  clientParams.putAll(params);
  PostMethod filePost=new PostMethod(uploadURL);
  try {
    ArrayList<Part> parts=new ArrayList<Part>();
    int fileUploadSize=0;
    for (    Map.Entry<String,File> fileEntry : files.entrySet()) {
      FilePart filePart=new FilePart(fileEntry.getKey(),fileEntry.getValue());
      parts.add(filePart);
      fileUploadSize+=filePart.length();
    }
    for (    Map.Entry<String,String> entry : clientParams.entrySet()) {
      parts.add(new StringPart(entry.getKey(),entry.getValue()));
    }
    String signature=calculateSignature(clientParams);
    parts.add(new StringPart("sig",signature));
    ProgressUploadEntity uploadEntity=new ProgressUploadEntity(parts.toArray(new Part[parts.size()]),filePost.getParams(),writeListener,fileUploadSize);
    filePost.setRequestEntity(uploadEntity);
    HttpClient client=HttpClientHelper.createClient(this.beesClientConfiguration);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    int status=client.executeMethod(filePost);
    String response=getResponseString(filePost.getResponseBodyAsStream());
    if (status == HttpStatus.SC_OK) {
      trace("upload complete, response=" + response);
    }
 else {
      trace("upload failed, response=" + HttpStatus.getStatusText(status));
      processError(response,status);
    }
    return response;
  }
  finally {
    filePost.releaseConnection();
  }
}
 

Example 31

From project core_1, under directory /test/src/main/java/org/switchyard/test/mixins/.

Source file: HTTPMixIn.java

  21 
vote

/** 
 * Send the specified request payload to the specified HTTP endpoint using the method specified.
 * @param endpointURL The HTTP endpoint URL.
 * @param request The request payload.
 * @param method The request method.
 * @return The HTTP response payload.
 */
public String sendString(String endpointURL,String request,String method){
  if (_dumpMessages) {
    _logger.info("Sending a " + method + " request to ["+ endpointURL+ "]");
    _logger.info("Request body:[" + request + "]");
  }
  try {
    if (method.equals(HTTP_PUT)) {
      PutMethod httpMethod=new PutMethod(endpointURL);
      httpMethod.setRequestEntity(new StringRequestEntity(request,_contentType,"UTF-8"));
      return execute(httpMethod);
    }
 else     if (method.equals(HTTP_POST)) {
      PostMethod httpMethod=new PostMethod(endpointURL);
      httpMethod.setRequestEntity(new StringRequestEntity(request,_contentType,"UTF-8"));
      return execute(httpMethod);
    }
 else     if (method.equals(HTTP_DELETE)) {
      DeleteMethod httpMethod=new DeleteMethod(endpointURL);
      return execute(httpMethod);
    }
 else     if (method.equals(HTTP_OPTIONS)) {
      OptionsMethod httpMethod=new OptionsMethod(endpointURL);
      return execute(httpMethod);
    }
 else     if (method.equals(HTTP_HEAD)) {
      HeadMethod httpMethod=new HeadMethod(endpointURL);
      return execute(httpMethod);
    }
 else {
      GetMethod httpMethod=new GetMethod(endpointURL);
      return execute(httpMethod);
    }
  }
 catch (  UnsupportedEncodingException e) {
    _logger.error("Unable to set request entity",e);
  }
  return null;
}
 

Example 32

From project Diver, under directory /ca.uvic.chisel.logging.eclipse/src/ca/uvic/chisel/logging/eclipse/internal/network/.

Source file: LogUploadRunnable.java

  21 
vote

public void run(IProgressMonitor sendMonitor) throws InterruptedException, InvocationTargetException {
  File[] filesToUpload=log.getCategory().getFilesToUpload();
  sendMonitor.beginTask("Uploading Log " + log.getCategory().getName(),filesToUpload.length);
  LoggingCategory category=log.getCategory();
  IMemento memento=category.getMemento();
  for (  File file : filesToUpload) {
    if (sendMonitor.isCanceled()) {
      throw new InterruptedException();
    }
    PostMethod post=new PostMethod(category.getURL().toString());
    try {
      Part[] parts={new StringPart("KIND","workbench-log"),new StringPart("CATEGORY",category.getCategoryID()),new StringPart("USER",WorkbenchLoggingPlugin.getDefault().getLocalUser()),new FilePart("WorkbenchLogger",file.getName(),file,"application/zip",null)};
      post.setRequestEntity(new MultipartRequestEntity(parts,post.getParams()));
      HttpClient client=new HttpClient();
      int status=client.executeMethod(post);
      String resp=getData(post.getResponseBodyAsStream());
      if (status != 200 || !resp.startsWith("Status: 200 Success")) {
        IOException ex=new IOException(resp);
        throw (ex);
      }
      memento.putString("lastUpload",file.getName());
      file.delete();
    }
 catch (    IOException e) {
      throw new InvocationTargetException(e);
    }
 finally {
      sendMonitor.worked(1);
    }
  }
  sendMonitor.done();
}
 

Example 33

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/location/.

Source file: ClientClass.java

  21 
vote

public boolean connectMe(){
  client=new HttpClient();
  postMethod=new PostMethod(uri);
  if (client == null)   return false;
 else {
    return true;
  }
}
 

Example 34

From project gatein-sso, under directory /agent/src/main/java/org/gatein/sso/agent/opensso/.

Source file: OpenSSOAgent.java

  21 
vote

private boolean isTokenValid(String token) throws Exception {
  HttpClient client=new HttpClient();
  PostMethod post=null;
  try {
    String url=this.serverUrl + "/identity/isTokenValid";
    post=new PostMethod(url);
    post.addParameter("tokenid",token);
    int status=client.executeMethod(post);
    String response=post.getResponseBodyAsString();
    log.debug("-------------------------------------------------------");
    log.debug("Status: " + status);
    log.debug("Response: " + response);
    log.debug("-------------------------------------------------------");
    if (response.contains(Boolean.TRUE.toString())) {
      return true;
    }
    return false;
  }
  finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
}
 

Example 35

From project GeoBI, under directory /print/src/test/java/integration/.

Source file: HeavyLoad.java

  21 
vote

private static void doQuery(){
  final ServerStats server;
synchronized (servers) {
    server=servers.first();
    servers.remove(server);
    server.addUsage();
    servers.add(server);
  }
  try {
    PostMethod method=new PostMethod(url);
    method.setRequestHeader("Connection","close");
    method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    if (!server.server.equals(DEFAULT)) {
      method.setRequestHeader("Cookie","SRV=" + server.server + "; path=/");
    }
    method.setRequestEntity(new StringRequestEntity(spec,"application/json","utf-8"));
    LOGGER.info("doing query... server=" + server.server);
    long start=System.currentTimeMillis();
    httpClient.executeMethod(method);
    if (method.getStatusCode() != 200) {
      LOGGER.error("Invalid status code: " + method.getStatusCode());
      System.exit(-1);
    }
    method.getResponseBody();
    final long duration=System.currentTimeMillis() - start;
    LOGGER.info("...query done in " + UnitUtilities.toElapsedTime(duration) + " server="+ server.updateStats(duration));
    method.releaseConnection();
  }
 catch (  IOException e) {
    LOGGER.error("server=" + server,e);
    System.exit(-1);
  }
}
 

Example 36

From project glimpse, under directory /glimpse-client/src/main/java/br/com/tecsinapse/glimpse/client/http/.

Source file: HttpInvoker.java

  21 
vote

public String invoke(String context,String body){
  try {
    HttpClient client=new HttpClient();
    PostMethod post=new PostMethod(url + context);
    String base64=username + ":" + password;
    post.setRequestHeader("Authorization","Basic " + new String(Base64.encodeBase64(base64.getBytes())));
    post.setRequestEntity(new StringRequestEntity(body,"text/plain","UTF-8"));
    int statusCode=client.executeMethod(post);
    StringBuilder builder=new StringBuilder();
    InputStream in=post.getResponseBodyAsStream();
    if (in != null) {
      int c=0;
      while ((c=in.read()) != -1) {
        builder.append((char)c);
      }
    }
    post.releaseConnection();
    if (statusCode == HttpStatus.SC_OK) {
      return builder.toString();
    }
 else     if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
      return "update\nStatus: " + statusCode + "\nUnauthorized Access, check your username and password.\nclose\n";
    }
 else {
      return "update\nStatus: " + statusCode + "\n"+ builder.toString()+ "\nclose\n";
    }
  }
 catch (  UnsupportedEncodingException e) {
    return exceptionResult(e);
  }
catch (  HttpException e) {
    return exceptionResult(e);
  }
catch (  IOException e) {
    return exceptionResult(e);
  }
}
 

Example 37

From project ihtika, under directory /Incubator/JenkinsHandler/src/main/java/khartn/jenkinshandler/.

Source file: SecuredMain.java

  21 
vote

/** 
 * On most security configurations, except "delegate to servlet container" authentication, simply sending in the BASIC authentication pre-emptively works. See http://hc.apache.org/httpclient-3.x/authentication.html for how to configure pre-emptive authentication. <p> However, in the "delegate to servlet container" mode, BASIC auth support depends on the container implementation, and hence inherently unreliable. The following code uses Jakarta Commons HTTP client to work around this problem by essentially emulating what the user does through the browser. <p> The code first emulates a click of the "login" link, then submit the login form. Once that's done, you are authenticated, so you can access the information you wanted. This is all possible because {@link HttpClient} maintains a cookie jar in it.
 */
public static void main(String[] args) throws IOException {
  HttpClient client=new HttpClient();
  String hostName="https://ihtika-hantest.rhcloud.com/";
  GetMethod loginLink=new GetMethod(hostName + "loginEntry");
  client.executeMethod(loginLink);
  checkResult(loginLink.getStatusCode());
  String location=hostName + "j_acegi_security_check";
  while (true) {
    PostMethod loginMethod=new PostMethod(location);
    loginMethod.addParameter("j_username","externaluser");
    loginMethod.addParameter("j_password","externaluser");
    loginMethod.addParameter("action","login");
    client.executeMethod(loginMethod);
    if (loginMethod.getStatusCode() / 100 == 3) {
      location=loginMethod.getResponseHeader("Location").getValue();
      continue;
    }
    System.out.println(loginMethod.getStatusCode());
    checkResult(loginMethod.getStatusCode());
    break;
  }
  HttpMethod method=new GetMethod(hostName + "/job/ihtika-build/build");
  client.executeMethod(method);
  System.out.println(method.getStatusCode());
}
 

Example 38

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/ontologiser/logic/impl/.

Source file: AnnotatorSearchClient.java

  21 
vote

public Map<String,Map<String,AnnotatorResult>> searchForTerms(Set<String> terms,String ontologiesToSearchOn,boolean wholeWordOnly){
  try {
    HttpClient client=new HttpClient();
    PostMethod method=new PostMethod(BASE_QUERY_URL);
    method.addParameter("wholeWordOnly",wholeWordOnly ? " true" : "false");
    method.addParameter("scored","true");
    method.addParameter("ontologiesToKeepInResult",ontologiesToSearchOn);
    method.addParameter("isVirtualOntologyId","true");
    method.addParameter("withSynonyms","true");
    method.addParameter("textToAnnotate",flattenSetToString(terms));
    method.addParameter("apikey","fd88ee35-6995-475d-b15a-85f1b9dd7a42");
    try {
      HostConfiguration configuration=new HostConfiguration();
      configuration.setHost("http://rest.bioontology.org");
      configuration.setProxy(System.getProperty("http.proxyHost"),Integer.valueOf(System.getProperty("http.proxyPort")));
      client.setHostConfiguration(configuration);
    }
 catch (    Exception e) {
      System.err.println("Problem encountered setting proxy for annotator search");
    }
    int statusCode=client.executeMethod(method);
    if (statusCode != -1) {
      String contents=method.getResponseBodyAsString();
      method.releaseConnection();
      return processContent(contents,terms);
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 39

From project iserve, under directory /iserve-parent/iserve-sal-gwt/src/main/java/uk/ac/open/kmi/iserve/sal/gwt/server/util/.

Source file: LufConnector.java

  21 
vote

public boolean reviewService(URI serviceUri,URI userUri,Rating rating,Comment comment) throws HttpException, IOException {
  if (null == serviceUri || null == serviceUri.toString() || serviceUri.toString().equals("") || null == userUri || null == userUri.toString() || userUri.toString().equals("")) {
    return false;
  }
  if (rating != null && rating.getValue() != 0) {
    PostMethod postRating=new PostMethod(ratingApiUri);
    postRating.addParameter("itemId",serviceUri.toString());
    postRating.addParameter("userId",userUri.toString());
    postRating.addParameter("rating","" + rating.getValue());
    int statusCode=client.executeMethod(postRating);
    if (statusCode != HttpStatus.SC_OK) {
      return false;
    }
  }
  if (comment != null && comment.getContent() != null && !comment.equals("")) {
    PostMethod postComment=new PostMethod(commentApiUri);
    postComment.addParameter("itemId",serviceUri.toString());
    postComment.addParameter("userId",userUri.toString());
    postComment.addParameter("comment","" + comment.getContent());
    int statusCode=client.executeMethod(postComment);
    if (statusCode != HttpStatus.SC_OK) {
      return false;
    }
  }
  return true;
}
 

Example 40

From project jabox, under directory /cis-hudson/src/main/java/org/jabox/cis/hudson/.

Source file: HudsonConnector.java

  21 
vote

/** 
 * Implementation inspired by groovy code here: http://wiki.hudson-ci.org/display/HUDSON/Authenticating+scripted+clients
 */
public boolean addProject(final Project project,final CISConnectorConfig dc) throws IOException, SAXException {
  HudsonConnectorConfig hcc=(HudsonConnectorConfig)dc;
  String url=dc.getServer().getUrl();
  HttpClient client=new HttpClient();
  client.getState().setCredentials(null,null,new UsernamePasswordCredentials(hcc.getUsername(),hcc.getPassword()));
  client.getState().setAuthenticationPreemptive(true);
  String uri=url + "createItem?name=" + project.getName();
  PostMethod post=new PostMethod(uri);
  post.setDoAuthentication(true);
  post.setRequestHeader("Content-type","text/xml; charset=UTF-8");
  InputStream is=getConfigXMLStream(project);
  String body=parseInputStream(is,project);
  post.setRequestBody(body);
  try {
    int result=client.executeMethod(post);
    System.out.println("Return code: " + result);
    for (    Header header : post.getResponseHeaders()) {
      System.out.println(header.toString().trim());
    }
    System.out.println(post.getResponseBodyAsString());
  }
  finally {
    post.releaseConnection();
  }
  PostMethod triggerBuild=new PostMethod(url + "/job/" + project.getName()+ "/build");
  client.executeMethod(triggerBuild);
  return true;
}
 

Example 41

From project jagger, under directory /chassis/coordinator.http/src/main/java/com/griddynamics/jagger/coordinator/http/client/.

Source file: ExchangeClient.java

  21 
vote

private String exchangeData(String url,Serializable obj) throws IOException {
  PostMethod method=new PostMethod(urlBase + url);
  NameValuePair pair=new NameValuePair();
  pair.setName(MESSAGE);
  pair.setValue(SerializationUtils.toString(obj));
  method.setQueryString(new NameValuePair[]{pair});
  try {
    int returnCode=httpClient.executeMethod(method);
    log.debug("Exchange response code {}",returnCode);
    return method.getResponseBodyAsString();
  }
  finally {
    try {
      method.releaseConnection();
    }
 catch (    Throwable e) {
      log.error("Cannot release connection",e);
    }
  }
}
 

Example 42

From project jbpm-form-builder, under directory /jbpm-gwt-form-builder/src/main/java/org/jbpm/formbuilder/server/file/.

Source file: GuvnorFileService.java

  21 
vote

@Override public String storeFile(String packageName,String fileName,byte[] content) throws FileException {
  try {
    String assetName=stripFileExtension(fileName);
    String assetExt=extractFileExtension(fileName);
    deleteOlderVersion(packageName,fileName);
    HttpClient client=helper.getHttpClient();
    String createUrl=helper.getRestBaseUrl() + URLEncoder.encode(packageName,GuvnorHelper.ENCODING) + "/assets/";
    PostMethod create=helper.createPostMethod(createUrl);
    try {
      helper.setAuth(client,create);
      create.addRequestHeader("Content-Type","application/octet-stream");
      create.addRequestHeader("Accept","application/atom+xml");
      create.addRequestHeader("Slug",assetName + '.' + assetExt);
      create.setRequestEntity(new ByteArrayRequestEntity(content));
      client.executeMethod(create);
    }
  finally {
      create.releaseConnection();
    }
    return (this.baseUrl + "/org.drools.guvnor.Guvnor/api/packages/" + URLEncoder.encode(packageName,GuvnorHelper.ENCODING)+ "/"+ URLEncoder.encode(assetName,GuvnorHelper.ENCODING)+ "."+ assetExt);
  }
 catch (  Exception e) {
    throw new FileException("Problem storing file",e);
  }
}
 

Example 43

From project jenkins-control-plugin, under directory /src/main/java/org/codinjutsu/tools/jenkins/security/.

Source file: BasicSecurityClient.java

  21 
vote

private void doAuthentication(URL jenkinsUrl) throws AuthenticationException {
  if (username != null && password != null) {
    httpClient.getState().setCredentials(new AuthScope(jenkinsUrl.getHost(),jenkinsUrl.getPort()),new UsernamePasswordCredentials(username,password));
  }
  httpClient.getParams().setAuthenticationPreemptive(true);
  PostMethod post=new PostMethod(jenkinsUrl.toString());
  InputStream inputStream=null;
  try {
    if (isCrumbDataSet()) {
      post.addRequestHeader(CRUMB_NAME,crumbValue);
    }
    post.setDoAuthentication(true);
    int responseCode=httpClient.executeMethod(post);
    inputStream=post.getResponseBodyAsStream();
    String responseBody=IOUtils.toString(inputStream,post.getResponseCharSet());
    if (responseCode != HttpURLConnection.HTTP_OK) {
      checkResponse(responseCode,responseBody);
    }
  }
 catch (  HttpException httpEx) {
    throw new ConfigurationException(String.format("Error during method execution %s",jenkinsUrl.toString()),httpEx);
  }
catch (  IOException ioEx) {
    throw new ConfigurationException(String.format("Error during method execution %s",jenkinsUrl.toString()),ioEx);
  }
 finally {
    IOUtils.closeQuietly(inputStream);
    post.releaseConnection();
  }
}
 

Example 44

From project jsf-test, under directory /jetty/src/main/java/org/jboss/test/faces/jetty/.

Source file: JettyServer.java

  21 
vote

@Override public void execute(){
switch (getRequestMethod()) {
case GET:
    this.httpClientMethod=new GetMethod(url.toExternalForm());
  break;
case POST:
PostMethod postMethod=new PostMethod(url.toExternalForm());
if (null != requestBody) {
try {
  RequestEntity body=new StringRequestEntity(requestBody,requestContentType,requestEncoding);
  postMethod.setRequestEntity(body);
}
 catch (UnsupportedEncodingException e) {
  throw new TestException(e);
}
}
this.httpClientMethod=postMethod;
break;
default :
throw new UnsupportedOperationException("Http Method " + getRequestMethod() + " is not supported");
}
String queryString=getRequestQueryString();
try {
if (null != queryString) {
httpClientMethod.setQueryString(queryString);
}
for (Map.Entry<String,String> entry : requestHeaders.entrySet()) {
httpClientMethod.addRequestHeader(entry.getKey(),entry.getValue());
}
this.statusCode=client.executeMethod(httpClientMethod);
}
 catch (IOException e) {
throw new TestException(e);
}
}
 

Example 45

From project lime-mvc, under directory /test/org/zdevra/guice/mvc/case9/.

Source file: Case9Test.java

  21 
vote

@Test public void testPostPeople() throws InterruptedException, HttpException, IOException {
  HttpMethod req=new PostMethod("http://localhost:9191/case9/people/rest");
  client.executeMethod(req);
  String out=req.getResponseBodyAsString();
  Assert.assertEquals("FORM POST",out);
}
 

Example 46

From project mapfish-print, under directory /src/test/java/integration/.

Source file: HeavyLoad.java

  21 
vote

private static void doQuery(){
  final ServerStats server;
synchronized (servers) {
    server=servers.first();
    servers.remove(server);
    server.addUsage();
    servers.add(server);
  }
  try {
    PostMethod method=new PostMethod(url);
    method.setRequestHeader("Connection","close");
    method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    if (!server.server.equals(DEFAULT)) {
      method.setRequestHeader("Cookie","SRV=" + server.server + "; path=/");
    }
    method.setRequestEntity(new StringRequestEntity(spec,"application/json","utf-8"));
    LOGGER.info("doing query... server=" + server.server);
    long start=System.currentTimeMillis();
    httpClient.executeMethod(method);
    if (method.getStatusCode() != 200) {
      LOGGER.error("Invalid status code: " + method.getStatusCode());
      System.exit(-1);
    }
    method.getResponseBody();
    final long duration=System.currentTimeMillis() - start;
    LOGGER.info("...query done in " + UnitUtilities.toElapsedTime(duration) + " server="+ server.updateStats(duration));
    method.releaseConnection();
  }
 catch (  IOException e) {
    LOGGER.error("server=" + server,e);
    System.exit(-1);
  }
}
 

Example 47

From project mapfish-print_1, under directory /src/test/java/integration/.

Source file: HeavyLoad.java

  21 
vote

private static void doQuery(){
  final ServerStats server;
synchronized (servers) {
    server=servers.first();
    servers.remove(server);
    server.addUsage();
    servers.add(server);
  }
  try {
    PostMethod method=new PostMethod(url);
    method.setRequestHeader("Connection","close");
    method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    if (!server.server.equals(DEFAULT)) {
      method.setRequestHeader("Cookie","SRV=" + server.server + "; path=/");
    }
    method.setRequestEntity(new StringRequestEntity(spec,"application/json","utf-8"));
    LOGGER.info("doing query... server=" + server.server);
    long start=System.currentTimeMillis();
    httpClient.executeMethod(method);
    if (method.getStatusCode() != 200) {
      LOGGER.error("Invalid status code: " + method.getStatusCode());
      System.exit(-1);
    }
    method.getResponseBody();
    final long duration=System.currentTimeMillis() - start;
    LOGGER.info("...query done in " + UnitUtilities.toElapsedTime(duration) + " server="+ server.updateStats(duration));
    method.releaseConnection();
  }
 catch (  IOException e) {
    LOGGER.error("server=" + server,e);
    System.exit(-1);
  }
}
 

Example 48

From project Metamorphosis, under directory /metamorphosis-http-client/src/main/java/com/taobao/metamorphosis/client/http/.

Source file: SimpleHttpProducer.java

  21 
vote

/** 
 * ????
 * @param message
 * @throws MetaClientException
 */
public SendResult sendMessage(final Message message,final Partition partition) throws MetaClientException {
  final long start=System.currentTimeMillis();
  this.checkMessage(message);
  final int flag=MessageFlagUtils.getFlag(message);
  final byte[] data=SimpleMessageProducer.encodeData(message);
  final String uri="/put/" + partition.getBrokerId() + "?topic="+ message.getTopic()+ "&partition="+ partition.getPartition()+ "&flag="+ flag+ "&length="+ data.length;
  final PostMethod postMethod=new PostMethod(uri);
  try {
    postMethod.setRequestEntity(new ByteArrayRequestEntity(data));
    this.httpclient.executeMethod(postMethod);
    final String resultStr=postMethod.getResponseBodyAsString();
switch (postMethod.getStatusCode()) {
case HttpStatus.Success:
{
        final String[] tmps=RESULT_SPLITER.split(resultStr);
        MessageAccessor.setId(message,Long.parseLong(tmps[0]));
        return new SendResult(true,new Partition(0,Integer.parseInt(tmps[1])),Long.parseLong(tmps[2]),null);
      }
case HttpStatus.Forbidden:
{
      return new SendResult(false,null,-1,String.valueOf(HttpStatus.Forbidden));
    }
default :
  return new SendResult(false,null,-1,resultStr);
}
}
 catch (final Exception e) {
this.logger.error(e.getMessage(),e);
throw new MetaClientException(e);
}
 finally {
final long duration=System.currentTimeMillis() - start;
System.out.println(duration);
MetaStatLog.addStatValue2(null,StatConstants.PUT_TIME_STAT,message.getTopic(),duration);
postMethod.releaseConnection();
}
}
 

Example 49

From project modules-set, under directory /webClipping/src/main/java/org/jahia/modules/filter/.

Source file: WebClippingFilter.java

  21 
vote

private String getURLContentWithPostMethod(String urlToClip,RenderContext renderContext,Resource resource,RenderChain chain,Map map){
  String path=urlToClip;
  Map parameters=(Map)map.get("URL_PARAMS");
  HttpClient httpClient=new HttpClient();
  Protocol.registerProtocol("https",new Protocol("https",new EasySSLProtocolSocketFactory(),443));
  httpClient.getParams().setContentCharset("UTF-8");
  PostMethod postMethod=new PostMethod(path);
  postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3,false));
  if (parameters != null) {
    Iterator iterator=parameters.entrySet().iterator();
    StringBuffer buffer=new StringBuffer(4096);
    while (iterator.hasNext()) {
      Map.Entry entry=(Map.Entry)iterator.next();
      if (!entry.getKey().toString().equals("original_method") && !entry.getKey().toString().equals("jahia_url_web_clipping")) {
        final Object value=entry.getValue();
        if (value instanceof String[]) {
          buffer.setLength(0);
          String[] strings=(String[])entry.getValue();
          for (int i=0; i < strings.length; i++) {
            String string=strings[i];
            buffer.append((i != 0) ? "," : "").append(string);
          }
          postMethod.addParameter(entry.getKey().toString(),buffer.toString());
        }
 else {
          postMethod.addParameter(entry.getKey().toString(),value.toString());
        }
      }
    }
  }
  String contentCharset=httpClient.getParams().getContentCharset();
  httpClient.getParams().setContentCharset(contentCharset);
  return getResponse(path,renderContext,resource,chain,postMethod,httpClient);
}
 

Example 50

From project onebusaway-nyc, under directory /onebusaway-nyc-integration-tests/src/test/java/org/onebusaway/nyc/integration_tests/.

Source file: TraceSupport.java

  21 
vote

public String uploadTraceForSimulation(String fileName,InputStream in,boolean _bypassInference) throws IOException {
  try {
    HttpClient client=new HttpClient();
    String url=url("/vehicle-location-simulation!upload-trace.do");
    PostMethod post=new PostMethod(url);
    ByteArrayPartSource source=getResourceAsPartSource(fileName,in);
    FilePart filePart=new FilePart("file",source);
    StringPart returnIdParam=new StringPart("returnId","true");
    StringPart shiftStartTimeParam=new StringPart("shiftStartTime","" + shiftStartTime);
    StringPart traceTypeParam=new StringPart("traceType","NycTestInferredLocationRecord");
    StringPart historySize=new StringPart("historySize","" + 0);
    StringPart bypassInference=new StringPart("bypassInference","false");
    if (_bypassInference == true) {
      bypassInference=new StringPart("bypassInference","true");
    }
    post.setRequestEntity(new MultipartRequestEntity(new Part[]{filePart,returnIdParam,shiftStartTimeParam,traceTypeParam,historySize,bypassInference},new HttpMethodParams()));
    client.executeMethod(post);
    return post.getResponseBodyAsString();
  }
 catch (  HttpException ex) {
    throw new IllegalStateException(ex);
  }
}
 

Example 51

From project org.eclipse.mylyn.github, under directory /org.eclipse.mylyn.github.core/src/org/eclipse/mylyn/github/internal/.

Source file: GitHubService.java

  21 
vote

/** 
 * Verify that the provided credentials are correct
 * @param credentials
 * @return true if and only if the credentials are correct
 */
public boolean verifyCredentials(GitHubCredentials credentials) throws GitHubServiceException {
  PostMethod method=null;
  boolean success=false;
  try {
    method=new PostMethod(gitURLBase + gitUserRoot + EMAILS);
    final NameValuePair login=new NameValuePair("login",credentials.getUsername());
    final NameValuePair token=new NameValuePair("token",credentials.getApiToken());
    method.setRequestBody(new NameValuePair[]{login,token});
    executeMethod(method);
    success=true;
  }
 catch (  PermissionDeniedException e) {
    return false;
  }
catch (  GitHubServiceException e) {
    throw e;
  }
catch (  final RuntimeException runtimeException) {
    throw runtimeException;
  }
catch (  final Exception exception) {
    throw new GitHubServiceException(exception);
  }
 finally {
    if (method != null)     method.releaseConnection();
  }
  return success;
}
 

Example 52

From project packetsamurai, under directory /src/com/l2j/packetsamurai/logrepo/.

Source file: RemoteLogRepositoryBackend.java

  21 
vote

public void updateLogDetails(LogFile logFile){
  CompoundXmlRequest req=new CompoundXmlRequest();
  PostMethod post=new PostMethod(_repoLocation + _repoRequestScript);
  Request updateRequest=req.createRequest("update");
  updateRequest.addPart("logname",logFile.getName());
  updateRequest.addPart("analyzerflags",Long.toString(logFile.getAnalyserBitSet()));
  updateRequest.addPart("comments",logFile.getComments());
  NameValuePair[] data={new NameValuePair("user",getUserName()),new NameValuePair("pass",getPassword()),new NameValuePair("req",req.toXml())};
  post.setRequestBody(data);
  try {
    int response=_httpClient.executeMethod(post);
    if (response != HttpStatus.SC_OK) {
      System.out.println("a\n" + post.getResponseBodyAsString());
    }
 else {
      System.out.println(post.getResponseBodyAsString());
    }
  }
 catch (  HttpException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 53

From project PIE, under directory /R2/pie-runtime/src/main/java/com/pieframework/runtime/utils/.

Source file: CampfireNotifier.java

  21 
vote

public static boolean notify(String msg,String url,String user,String password){
  HttpClient client=new HttpClient();
  PostMethod post=new PostMethod(url);
  byte[] encodedPassword=(user + ":" + password).getBytes();
  BASE64Encoder encoder=new BASE64Encoder();
  post.setRequestHeader("Authorization","Basic " + encoder.encode(encodedPassword));
  try {
    RequestEntity entity=new StringRequestEntity("<message><body>" + msg + "</body></message>","application/xml","UTF-8");
    post.setRequestEntity(entity);
    client.executeMethod(post);
    String responseMsg="httpStatus: " + post.getStatusCode() + " "+ "Content-type: "+ post.getResponseHeader("Content-Type")+ " "+ post.getResponseBodyAsString();
    Configuration.log().info(responseMsg);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return true;
}
 

Example 54

From project riftsaw-ode, under directory /tools/src/main/java/org/apache/ode/tools/sendsoap/cline/.

Source file: HttpSoapSender.java

  21 
vote

public static String doSend(URL u,InputStream is,String proxyServer,int proxyPort,String username,String password,String soapAction) throws IOException {
  ByteArrayOutputStream bos=new ByteArrayOutputStream(8192);
  StreamUtils.copy(bos,is);
  String now=Long.toString(System.currentTimeMillis());
  int c=1;
  String data=new String(bos.toByteArray());
  Matcher m=SEQ.matcher(data);
  StringBuffer sb=new StringBuffer(8192);
  while (m.find()) {
    m.appendReplacement(sb,now + "-" + c++);
  }
  m.appendTail(sb);
  SimpleHttpConnectionManager mgr=new SimpleHttpConnectionManager();
  mgr.getParams().setConnectionTimeout(60000);
  mgr.getParams().setSoTimeout(60000);
  HttpClient httpClient=new HttpClient(mgr);
  PostMethod httpPostMethod=new PostMethod(u.toExternalForm());
  if (proxyServer != null && proxyServer.length() > 0) {
    httpClient.getState().setCredentials(new AuthScope(proxyServer,proxyPort),new UsernamePasswordCredentials(username,password));
    httpPostMethod.setDoAuthentication(true);
  }
  if (soapAction == null)   soapAction="";
  httpPostMethod.setRequestHeader("SOAPAction","\"" + soapAction + "\"");
  httpPostMethod.setRequestHeader("Content-Type","text/xml");
  httpPostMethod.setRequestEntity(new StringRequestEntity(sb.toString()));
  httpClient.executeMethod(httpPostMethod);
  return httpPostMethod.getResponseBodyAsString() + "\n";
}
 

Example 55

From project sparqled, under directory /recommendation-servlet/src/test/java/org/sindice/analytics/servlet/.

Source file: TestAssistedSparqlEditorSevlet.java

  21 
vote

@Test public void testPredicateRecommendation() throws IllegalArgumentException, HttpException, IOException {
  final String query="SELECT * { ?s < ?o }";
  PostMethod post=new PostMethod(aseBaseUrl);
  post.addParameter(Protocol.QUERY_PARAM_NAME,URLEncoder.encode(query,"UTF-8"));
  post.addParameter(AssistedSparqlEditorServlet.DATA_REQUEST,"autocomplete");
  post.addParameter(AssistedSparqlEditorServlet.RESPONSE,ResponseType.JSON.toString());
  final int code=client.executeMethod(post);
  if (code == HttpStatus.SC_OK) {
    final String json=post.getResponseBodyAsString();
    final ObjectMapper mapper=new ObjectMapper();
    final HashMap<String,Object> jsonMap=mapper.readValue(json,HashMap.class);
    final ArrayList<Results> expectedResults=new ArrayList<Results>(){
{
        add(new Results(2,"http://www.di.unipi.it/#produce"));
        add(new Results(1,"http://www.di.unipi.it/#livein"));
      }
    }
;
    checkResponse(jsonMap,expectedResults,false,false);
  }
 else {
    fail("code=" + code);
  }
}
 

Example 56

From project spring-security-saml, under directory /saml2-core/src/main/java/org/springframework/security/saml/websso/.

Source file: ArtifactResolutionProfileImpl.java

  21 
vote

/** 
 * Uses HTTPClient to send and retrieve ArtifactMessages.
 * @param endpointURI URI incoming artifactMessage is addressed to
 * @param context     context with filled communicationProfileId, outboundMessage, outboundSAMLMessage, peerEntityEndpoint, peerEntityId, peerEntityMetadata, peerEntityRole, peerEntityRoleMetadata
 * @throws SAMLException             error processing artifact messages
 * @throws MessageEncodingException  error sending artifactRequest
 * @throws MessageDecodingException  error retrieving artifactResponse
 * @throws MetadataProviderException error resolving metadata
 * @throws org.opensaml.xml.security.SecurityException invalid message signature
 */
protected void getArtifactResponse(String endpointURI,SAMLMessageContext context) throws SAMLException, MessageEncodingException, MessageDecodingException, MetadataProviderException, org.opensaml.xml.security.SecurityException {
  PostMethod postMethod=null;
  try {
    URI uri=new URI(context.getPeerEntityEndpoint().getLocation(),true,"UTF-8");
    postMethod=new PostMethod();
    postMethod.setPath(uri.getPath());
    HostConfiguration hc=getHostConfiguration(uri,context);
    HttpClientOutTransport clientOutTransport=new HttpClientOutTransport(postMethod);
    HttpClientInTransport clientInTransport=new HttpClientInTransport(postMethod,endpointURI);
    context.setInboundMessageTransport(clientInTransport);
    context.setOutboundMessageTransport(clientOutTransport);
    boolean signMessage=context.getPeerExtendedMetadata().isRequireArtifactResolveSigned();
    processor.sendMessage(context,signMessage,SAMLConstants.SAML2_SOAP11_BINDING_URI);
    int responseCode=httpClient.executeMethod(hc,postMethod);
    if (responseCode != 200) {
      String responseBody=postMethod.getResponseBodyAsString();
      log.debug("Problem communicating with Artifact Resolution service, received response {}, body {}.",responseCode,responseBody);
      throw new MessageDecodingException("Problem communicating with Artifact Resolution service, received response " + responseCode + ", body "+ responseBody);
    }
    processor.retrieveMessage(context,SAMLConstants.SAML2_SOAP11_BINDING_URI);
  }
 catch (  IOException e) {
    log.debug("Error when sending request to artifact resolution service.",e);
    throw new MessageDecodingException("Error when sending request to artifact resolution service.",e);
  }
 finally {
    if (postMethod != null) {
      postMethod.releaseConnection();
    }
  }
}
 

Example 57

From project tb-diamond_1, under directory /diamond-client/src/main/java/com/taobao/diamond/client/impl/.

Source file: DefaultDiamondPublisher.java

  21 
vote

private void login() throws Exception {
  PostMethod loginMethod=new PostMethod(getLoginUri());
  NameValuePair username_value=new NameValuePair("username",userName);
  NameValuePair password_value=new NameValuePair("password",password);
  loginMethod.addRequestHeader(Constants.APPNAME,this.appName);
  loginMethod.setRequestBody(new NameValuePair[]{username_value,password_value});
  this.configureHttpMethod(loginMethod);
  log.info("server list:" + this.diamondConfigure.getDomainNameList());
  log.info("index=" + this.domainNamePos.get());
  httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(domainNamePos.get()),diamondConfigure.getPort());
  try {
    int statusCode=httpClient.executeMethod(loginMethod);
    String responseMsg=loginMethod.getResponseBodyAsString();
    if (statusCode == HttpStatus.SC_OK) {
      log.info("????");
    }
 else {
      log.error("?????????" + responseMsg + ", ?????"+ statusCode);
      throw new Exception("????, ??????????");
    }
  }
  finally {
    loginMethod.releaseConnection();
  }
}
 

Example 58

From project twitter-2-weibo, under directory /core/src/main/java/weibo4j/http/.

Source file: HttpClient.java

  21 
vote

public Response post(String url,PostParameter[] params,Boolean WithTokenHeader) throws WeiboException {
  log("Request:");
  log("POST" + url);
  PostMethod postMethod=new PostMethod(url);
  for (int i=0; i < params.length; i++) {
    postMethod.addParameter(params[i].getName(),params[i].getValue());
  }
  HttpMethodParams param=postMethod.getParams();
  param.setContentCharset("UTF-8");
  if (WithTokenHeader) {
    return httpRequest(postMethod);
  }
 else {
    return httpRequest(postMethod,WithTokenHeader);
  }
}
 

Example 59

From project upm-swing, under directory /src/com/_17od/upm/transport/.

Source file: HTTPTransport.java

  21 
vote

public void put(String targetLocation,File file,String username,String password) throws TransportException {
  targetLocation=addTrailingSlash(targetLocation) + "upload.php";
  PostMethod post=new PostMethod(targetLocation);
  try {
    Part[] parts={new FilePart("userfile",file)};
    post.setRequestEntity(new MultipartRequestEntity(parts,post.getParams()));
    if (username != null) {
      Credentials creds=new UsernamePasswordCredentials(new String(username),new String(password));
      URL url=new URL(targetLocation);
      AuthScope authScope=new AuthScope(url.getHost(),url.getPort());
      client.getState().setCredentials(authScope,creds);
      client.getParams().setAuthenticationPreemptive(true);
    }
    int status=client.executeMethod(post);
    if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) {
      status=client.executeMethod(post);
    }
    if (status != HttpStatus.SC_OK) {
      throw new TransportException("There's been some kind of problem uploading a file to the HTTP server.\n\nThe HTTP error message is [" + HttpStatus.getStatusText(status) + "]");
    }
    if (!post.getResponseBodyAsString().equals("OK")) {
      throw new TransportException("There's been some kind of problem uploading a file to the HTTP server.\n\nThe error message is [" + post.getResponseBodyAsString() + "]");
    }
  }
 catch (  FileNotFoundException e) {
    throw new TransportException(e);
  }
catch (  MalformedURLException e) {
    throw new TransportException(e);
  }
catch (  HttpException e) {
    throw new TransportException(e);
  }
catch (  IOException e) {
    throw new TransportException(e);
  }
 finally {
    post.releaseConnection();
  }
}
 

Example 60

From project virgo.web, under directory /org.eclipse.virgo.web.test/src/test/java/org/eclipse/virgo/web/test/.

Source file: AbstractWebIntegrationTests.java

  21 
vote

/** 
 * @param context the context path of the web-app, which if non-null, will be prepended to the resource path
 * @param resource the resource path to test against
 * @param params parameters in the form of name-value pairs to be passed in the initial POST request
 * @param followRedirectsForGet whether or not to automatically follow redirects for a GET request following theinitial POST request
 * @param expectedPostResponseCode the expected HTTP response code for the initial POST request
 * @param expectedGetAfterPostResponseCode the expected HTTP response code for the subsequent GET request
 * @param expectedContents text expected to exist in the returned resource
 */
protected void assertPostRequest(String context,String resource,Map<String,String> params,boolean followRedirectsForGet,int expectedPostResponseCode,int expectedGetAfterPostResponseCode,String expectedContents) throws Exception {
  final String address="http://localhost:8080/" + (context == null ? "" : context + "/") + resource;
  System.out.println("AbstractWebIntegrationTests: executing POST request for [" + address + "].");
  final PostMethod post=new PostMethod(address);
  for (  String name : params.keySet()) {
    post.setParameter(name,params.get(name));
  }
  int responseCode=getHttpClient().executeMethod(post);
  assertEquals("Verifying HTTP POST response code for URL [" + address + "]",expectedPostResponseCode,responseCode);
  if (responseCode / 100 == 2 && expectedContents != null) {
    String body=post.getResponseBodyAsString();
    assertNotNull("The response body for URL [" + address + "] should not be null.",body);
    assertTrue("The response body for URL [" + address + "] should contain ["+ expectedContents+ "].",body.contains(expectedContents));
  }
 else   if (responseCode == SC_FOUND && expectedContents != null) {
    String location=post.getResponseHeader("Location").getValue();
    assertGetRequest(location,followRedirectsForGet,expectedGetAfterPostResponseCode,Arrays.asList(expectedContents));
  }
}
 

Example 61

From project jmeter-components, under directory /src/main/java/com/atlantbh/jmeter/plugins/oauth/.

Source file: OAuthSampler.java

  20 
vote

private HttpMethodBase createHttpMethod(String method,String urlStr){
  HttpMethodBase httpMethod;
  if (method.equals(POST)) {
    httpMethod=new PostMethod(urlStr);
  }
 else   if (method.equals(PUT)) {
    httpMethod=new PutMethod(urlStr);
  }
 else   if (method.equals(HEAD)) {
    httpMethod=new HeadMethod(urlStr);
  }
 else   if (method.equals(TRACE)) {
    httpMethod=new TraceMethod(urlStr);
  }
 else   if (method.equals(OPTIONS)) {
    httpMethod=new OptionsMethod(urlStr);
  }
 else   if (method.equals(DELETE)) {
    httpMethod=new DeleteMethod(urlStr);
  }
 else   if (method.equals(GET)) {
    httpMethod=new GetMethod(urlStr);
  }
 else {
    log.error("Unexpected method (converted to GET): " + method);
    httpMethod=new GetMethod(urlStr);
  }
  return httpMethod;
}
 

Example 62

From project nuxeo-chemistry, under directory /nuxeo-opencmis-tests/src/test/java/org/nuxeo/ecm/core/opencmis/impl/client/protocol/http/.

Source file: HttpURLConnection.java

  20 
vote

protected HttpMethod newMethod(String name){
  if ("GET".equals(name)) {
    return new GetMethod();
  }
  if ("POST".equals(name)) {
    return new PostMethod();
  }
  if ("DELETE".equals(name)) {
    return new DeleteMethod();
  }
  if ("PUT".equals(name)) {
    return new PutMethod();
  }
  throw new UnsupportedOperationException("Unsupported method " + name);
}
 

Example 63

From project nuxeo-services, under directory /nuxeo-platform-web-common/src/main/java/org/nuxeo/ecm/platform/web/common/ajax/.

Source file: AjaxProxyServlet.java

  20 
vote

protected static String doRequest(String method,String targetURL,HttpServletRequest req) throws IOException {
  HttpClient client=new HttpClient();
  HttpMethod httpMethod;
  if ("GET".equals(method)) {
    httpMethod=new GetMethod(targetURL);
  }
 else   if ("POST".equals(method)) {
    httpMethod=new PostMethod(targetURL);
    ((PostMethod)httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
  }
 else   if ("PUT".equals(method)) {
    httpMethod=new PutMethod(targetURL);
    ((PutMethod)httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
  }
 else {
    throw new IllegalStateException("Unknown HTTP method: " + method);
  }
  @SuppressWarnings("unchecked") Map<String,Object> params=req.getParameterMap();
  for (  String paramName : params.keySet()) {
    httpMethod.getParams().setParameter(paramName,params.get(paramName));
  }
  client.executeMethod(httpMethod);
  String body=httpMethod.getResponseBodyAsString();
  httpMethod.releaseConnection();
  return body;
}
 

Example 64

From project spring-android, under directory /spring-android-rest-template/src/main/java/org/springframework/http/client/.

Source file: CommonsClientHttpRequestFactory.java

  20 
vote

/** 
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod,String uri){
switch (httpMethod) {
case GET:
    return new GetMethod(uri);
case DELETE:
  return new DeleteMethod(uri);
case HEAD:
return new HeadMethod(uri);
case OPTIONS:
return new OptionsMethod(uri);
case POST:
return new PostMethod(uri);
case PUT:
return new PutMethod(uri);
case TRACE:
return new TraceMethod(uri);
default :
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}
 

Example 65

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/sender/.

Source file: AsyncAckSender.java

  19 
vote

@Override public List<CommitListEntry> postAndParseResponse(PostMethod method,List<CommitListEntry> expectedCommitResults) throws IOException, InterruptedException {
  adaptorReset.reportPending(expectedCommitResults);
  List<String> resp=reliablySend(method,ServletCollector.PATH);
  List<DelayedCommit> toDelay=new ArrayList<DelayedCommit>(resp.size());
  ArrayList<CommitListEntry> result=new ArrayList<CommitListEntry>();
  for (int i=0; i < resp.size(); ++i) {
    if (resp.get(i).startsWith(ServletCollector.ACK_PREFIX))     result.add(expectedCommitResults.get(i));
 else {
      CommitListEntry cle=expectedCommitResults.get(i);
      Matcher m=partialCommitPat.matcher(resp.get(i));
      if (!m.matches())       log.warn("unexpected response: " + resp.get(i));
 else       log.info("waiting for " + m.group(1) + " to hit "+ m.group(2)+ " before committing "+ agent.getAdaptorName(cle.adaptor));
      String name=agent.getAdaptorName(cle.adaptor);
      if (name != null)       toDelay.add(new DelayedCommit(cle.adaptor,cle.uuid,cle.start,m.group(1),Long.parseLong(m.group(2)),name));
    }
  }
  delayCommits(toDelay);
  return result;
}
 

Example 66

From project heritrix3, under directory /modules/src/main/java/org/archive/modules/.

Source file: CrawlURI.java

  19 
vote

public void setHttpMethod(HttpMethod method){
  this.method=method;
  if (method instanceof PostMethod) {
    fetchType=FetchType.HTTP_POST;
  }
 else   if (method instanceof GetMethod) {
    fetchType=FetchType.HTTP_GET;
  }
 else {
    fetchType=FetchType.UNKNOWN;
  }
}
 

Example 67

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/datacollection/sender/.

Source file: AsyncAckSender.java

  19 
vote

@Override public List<CommitListEntry> postAndParseResponse(PostMethod method,List<CommitListEntry> expectedCommitResults) throws IOException, InterruptedException {
  adaptorReset.reportPending(expectedCommitResults);
  List<String> resp=reliablySend(method,ServletCollector.PATH);
  List<DelayedCommit> toDelay=new ArrayList<DelayedCommit>(resp.size());
  ArrayList<CommitListEntry> result=new ArrayList<CommitListEntry>();
  for (int i=0; i < resp.size(); ++i) {
    if (resp.get(i).startsWith(ServletCollector.ACK_PREFIX))     result.add(expectedCommitResults.get(i));
 else {
      CommitListEntry cle=expectedCommitResults.get(i);
      Matcher m=partialCommitPat.matcher(resp.get(i));
      if (!m.matches())       log.warn("unexpected response: " + resp.get(i));
 else       log.info("waiting for " + m.group(1) + " to hit "+ m.group(2)+ " before committing "+ agent.getAdaptorName(cle.adaptor));
      String name=agent.getAdaptorName(cle.adaptor);
      if (name != null)       toDelay.add(new DelayedCommit(cle.adaptor,cle.uuid,cle.start,m.group(1),Long.parseLong(m.group(2)),name));
    }
  }
  delayCommits(toDelay);
  return result;
}
 

Example 68

From project httpcache4j, under directory /resolvers/resolvers-commons-httpclient/src/test/java/org/codehaus/httpcache4j/client/.

Source file: HTTPClientResponseResolverTest.java

  19 
vote

@Test public void testResolvePOSTWithNoHeaders() throws IOException {
  HTTPRequest request=new HTTPRequest(URI.create("http://dummy/uri/123"),HTTPMethod.POST);
  final Payload payload=mock(Payload.class);
  request=request.payload(payload);
  when(payload.getMimeType()).thenReturn(new MIMEType("text/plain"));
  final HttpMethod method=mock(PostMethod.class);
  HTTPClientResponseResolver resolver=createResponseResolver(method,Status.valueOf(201),new Header[0]);
  HTTPResponse response=resolver.resolve(request);
  assertNotNull(response);
  assertEquals(201,response.getStatus().getCode());
  assertEquals(0,response.getHeaders().size());
}
 

Example 69

From project isohealth, under directory /Oauth/java/jmeter/jmeter/src/main/java/org/apache/jmeter/protocol/oauth/sampler/.

Source file: OAuthSampler.java

  19 
vote

private String sendPostData(HttpMethod method) throws IOException {
  String form;
  if (useAuthHeader) {
    form=OAuth.formEncode(nonOAuthParams);
  }
 else {
    form=OAuth.formEncode(message.getParameters());
  }
  method.addRequestHeader(HEADER_CONTENT_TYPE,OAuth.FORM_ENCODED);
  method.addRequestHeader(HEADER_CONTENT_LENGTH,form.length() + "");
  if (method instanceof PostMethod || method instanceof PutMethod) {
    StringRequestEntity requestEntity=new StringRequestEntity(form,OAuth.FORM_ENCODED,OAuth.ENCODING);
    ((EntityEnclosingMethod)method).setRequestEntity(requestEntity);
  }
 else {
    log.error("Logic error, method must be POST or PUT to send body");
  }
  return form;
}
 

Example 70

From project rundeck, under directory /core/src/main/java/com/dtolabs/client/utils/.

Source file: WebserviceHttpClientChannel.java

  19 
vote

/** 
 * Returns the RequestEntity for the Post method request.  If a file upload is included, it will return a MultipartRequestEntity with the file as one part.  otherwise, null is returned.
 */
protected RequestEntity getRequestEntity(final PostMethod method){
  if (uploadFile != null) {
    logger.debug("attempting to upload file with colony request");
    try {
      final Part[] parts=new Part[]{new FilePart(null != getFileparam() ? getFileparam() : "uploadFile",uploadFile.getName(),uploadFile)};
      return new MultipartRequestEntity(parts,method.getParams());
    }
 catch (    FileNotFoundException e) {
      throw new CoreException("Could not upload file in request to server: " + uploadFile.getAbsolutePath(),e);
    }
  }
 else {
    return null;
  }
}