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

The following are top voted examples for showing how to use org.apache.commons.httpclient.methods.StringRequestEntity. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OSCAR-ConCert   File: OntarioMD.java   Source Code and License 8 votes vote down vote up
public Hashtable loginToOntarioMD(String username,String password,String incomingRequestor) throws Exception{
    //public ArrayList soapHttpCall(int siteCode, String userId, String passwd,		String xml) throws Exception
    Hashtable h  = null;
    PostMethod post = new PostMethod("https://www.ontariomd.ca/services/OMDAutomatedAuthentication");
    post.setRequestHeader("SOAPAction", "");
    post.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

    String soapMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:getSession xmlns:ns1=\"urn:OMDAutomatedAuthentication\"><username>"+username+"</username><password>"+password+"</password><incomingRequestor>"+incomingRequestor+"</incomingRequestor></ns1:getSession></soap:Body></soap:Envelope> ";

    RequestEntity re = new StringRequestEntity(soapMsg, "text/xml", "utf-8");

    post.setRequestEntity(re);

    HttpClient httpclient = new HttpClient();
    // Execute request
    try{
            httpclient.executeMethod(post);
            h = parseReturn(post.getResponseBodyAsStream());
    }catch(Exception e ){
        MiscUtils.getLogger().error("Error", e);
    } finally{
            // Release current connection to the connection pool
            post.releaseConnection();
    }
    return h;
}
 
Example 2
Project: lib-commons-httpclient   File: TestMethodCharEncoding.java   Source Code and License 7 votes vote down vote up
public void testRussianInRequestBody() throws IOException {
    PostMethod httppost = new PostMethod("/");
    String s = constructString(RUSSIAN_STUFF_UNICODE);
    // Test UTF-8 encoding
    httppost.setRequestEntity(
        new StringRequestEntity(s, "text/plain", CHARSET_UTF8));
    verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_UTF8);
    // Test KOI8-R
    httppost.setRequestEntity(
        new StringRequestEntity(s, "text/plain", CHARSET_KOI8_R));
    verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_KOI8R);
    // Test WIN1251
    httppost.setRequestEntity(
        new StringRequestEntity(s, "text/plain", CHARSET_WIN1251));
    verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_WIN1251);
}
 
Example 3
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 7 votes vote down vote up
/**
 * Tests POST via authenticating proxy + host auth + connection close 
 */
public void testPostProxyAuthHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 4
Project: DBus   File: HttpRequest.java   Source Code and License 6 votes vote down vote up
public String doPut(String url, String charset, String jsonObj) {
    String resStr = null;
    HttpClient htpClient = new HttpClient();
    PutMethod putMethod = new PutMethod(url);
    putMethod.getParams().setParameter(
            HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
    try {
        putMethod.setRequestEntity(new StringRequestEntity(jsonObj,
                "application/json", charset));
        int statusCode = htpClient.executeMethod(putMethod);
        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + putMethod.getStatusLine());
            return null;
        }
        byte[] responseBody = putMethod.getResponseBody();
        resStr = new String(responseBody, charset);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        putMethod.releaseConnection();
    }
    return resStr;
}
 
Example 5
Project: alfresco-remote-api   File: PublicApiHttpClient.java   Source Code and License 6 votes vote down vote up
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
            final String relationCollectionName, final Object relationshipEntityId, final String body, String contentType, final Map<String, String> params) throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
                relationshipEntityId, params);
    String url = endpoint.getUrl();

    PostMethod req = new PostMethod(url.toString());
    if (body != null)
    {
        if (contentType == null || contentType.isEmpty())
        {
            contentType = "application/json";
        }
        StringRequestEntity requestEntity = new StringRequestEntity(body, contentType, "UTF-8");
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example 6
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + host auth + connection keep-alive 
 */
public void testPostHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 7
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + host auth + connection close 
 */
public void testPostHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 8
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + invalid host auth 
 */
public void testPostHostInvalidAuth() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.client.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("testuser", "wrongstuff"));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode());
    } finally {
        post.releaseConnection();
    }
}
 
Example 9
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive 
 */
public void testPostInteractiveHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 10
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection close 
 */
public void testPostInteractiveHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
            
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 11
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via authenticating proxy
 */
public void testPostAuthProxy() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.server.setHttpService(new FeedbackService());

    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 12
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via authenticating proxy + host auth + connection keep-alive 
 */
public void testPostProxyAuthHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 13
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive 
 */
public void testPostInteractiveProxyAuthHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 14
Project: lib-commons-httpclient   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection close 
 */
public void testPostInteractiveProxyAuthHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
            
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 15
Project: Spring-Boot-Server   File: HttpUtils.java   Source Code and License 6 votes vote down vote up
public static String getPostResponseHeader(String url,String argJson,List<UHeader> headerList,String headerName){
  	String info = "";
  	try {
   	HttpClient client = new HttpClient();
	PostMethod method = new PostMethod(url);
	client.getParams().setContentCharset("UTF-8");
	if(headerList.size()>0){
		for(int i = 0;i<headerList.size();i++){
			UHeader header = headerList.get(i);
			method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
		}
	}
	method.getParams().setParameter(
			HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
	if(argJson != null && !argJson.trim().equals("")) {
		RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8");
		method.setRequestEntity(requestEntity);
	}
	method.releaseConnection();
	Header h =  method.getResponseHeader(headerName);
	info = h.getValue();
} catch (IOException e) {
	e.printStackTrace();
}
  	return info;
  }
 
Example 16
Project: scribe   File: ZenDeskTest.java   Source Code and License 6 votes vote down vote up
/**
 * creates a user in Zendesk. UserXml is passed as request body.
 * 
 * @param httpClient
 * @param userXml
 * @return
 * @throws HttpException
 * @throws IOException
 */
private int createUser(HttpClient httpClient, String userXml) throws Exception {

  PostMethod post = new PostMethod(cadURL + "/object/user?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new StringRequestEntity(userXml, "application/xml", "ISO-8859-1");
  post.setRequestEntity(entity);
  int result = 0;
  try {
    System.out.println("URI: " + post.getURI());
    result = httpClient.executeMethod(post);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + post.getResponseBodyAsString());

  } catch (final Exception e) {
    throw e;
  } finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
  return result;
}
 
Example 17
Project: scribe   File: MicroSoftLeadTest.java   Source Code and License 6 votes vote down vote up
/**
 * creates a Lead in MS. Lead Xml is passed as request body.
 * 
 * @param httpClient
 * @param leadXml
 * @return
 * @throws HttpException
 * @throws IOException
 */
private final int createLead(final HttpClient httpClient, final String leadXml) throws Exception {

  final PostMethod post = new PostMethod(cadURL + "/object/lead?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new StringRequestEntity(leadXml, "application/xml", "ISO-8859-1");
  post.setRequestEntity(entity);
  int result = 0;
  try {
    result = httpClient.executeMethod(post);
  } catch (final Exception e) {
    throw e;
  } finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
  return result;
}
 
Example 18
Project: scribe   File: MicroSoftOpportunityTest.java   Source Code and License 6 votes vote down vote up
/**
 * creates an opportunity in MS. opportunity Xml is passed as request body.
 * 
 * @param httpClient
 * @param opportunityXml
 * @return
 * @throws HttpException
 * @throws IOException
 */
private final int createOpportunity(final HttpClient httpClient, final String opportunityXml) throws Exception {

  final PostMethod post = new PostMethod(cadURL + "/object/opportunity?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  final RequestEntity entity = new StringRequestEntity(opportunityXml, "application/xml", "ISO-8859-1");
  post.setRequestEntity(entity);
  int result = 0;
  try {
    result = httpClient.executeMethod(post);
  } catch (final Exception e) {
    throw e;
  } finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
  return result;
}
 
Example 19
Project: scribe   File: MicroSoftTaskTest.java   Source Code and License 6 votes vote down vote up
/**
 * creates a task in MS. task Xml is passed as request body.
 * 
 * @param httpClient
 * @param taskXml
 * @return
 * @throws HttpException
 * @throws IOException
 */
private final int createTask(final HttpClient httpClient, final String taskXml) throws Exception {

  final PostMethod post = new PostMethod(cadURL + "/object/task?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  final RequestEntity entity = new StringRequestEntity(taskXml, "application/xml", "ISO-8859-1");
  post.setRequestEntity(entity);
  int result = 0;
  try {
    result = httpClient.executeMethod(post);
  } catch (final Exception e) {
    throw e;
  } finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
  return result;
}
 
Example 20
Project: scribe   File: MicroSoftIncidentTest.java   Source Code and License 6 votes vote down vote up
/**
 * creates an incident in MS. incident Xml is passed as request body.
 * 
 * @param httpClient
 * @param userXml
 * @return
 * @throws HttpException
 * @throws IOException
 */
private final int createIncident(final HttpClient httpClient, final String userXml) throws Exception {

  final PostMethod post = new PostMethod(cadURL + "/object/incident?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  final RequestEntity entity = new StringRequestEntity(userXml, "application/xml", "ISO-8859-1");
  post.setRequestEntity(entity);
  int result = 0;
  try {
    result = httpClient.executeMethod(post);
  } catch (final Exception e) {
    throw e;
  } finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
  return result;
}
 
Example 21
Project: scribe   File: MicroSoftContactTest.java   Source Code and License 6 votes vote down vote up
/**
 * creates a Contact in MS. contact XML is passed as request body.
 * 
 * @param httpClient
 * @param contactXml
 * @return
 * @throws HttpException
 * @throws IOException
 */
private final int createContact(final HttpClient httpClient, final String contactXml) throws Exception {

  final PostMethod post = new PostMethod(cadURL + "/object/contact?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  final RequestEntity entity = new StringRequestEntity(contactXml, "application/xml", "ISO-8859-1");
  post.setRequestEntity(entity);
  int result = 0;
  try {
    result = httpClient.executeMethod(post);
  } catch (final Exception e) {
    throw e;
  } finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
  return result;
}
 
Example 22
Project: scribe   File: MicroSoftAccountTest.java   Source Code and License 6 votes vote down vote up
/**
 * creates a account in MS. account Xml is passed as request body.
 * 
 * @param httpClient
 * @param accountXml
 * @return
 * @throws HttpException
 * @throws URIException
 */

private final int createAccount(final HttpClient httpClient, final String accountXml) throws Exception {

  final PostMethod post = new PostMethod(cadURL + "/object/account?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  final RequestEntity entity = new StringRequestEntity(accountXml, "application/xml", "ISO-8859-1");
  post.setRequestEntity(entity);
  int result = 0;
  try {
    result = httpClient.executeMethod(post);
  } catch (final Exception e) {
    throw e;
  } finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
  return result;
}
 
Example 23
Project: scribe   File: MSCRMOCPTest.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param url
 * @param soapEnvelope
 * @return
 * @throws UnsupportedEncodingException
 */
public final static String getSOAPResponse(final String url, final String soapEnvelope) throws UnsupportedEncodingException {

  final PostMethod postMethod = new PostMethod(url);
  postMethod.addRequestHeader("Content-Type", "application/soap+xml; charset=UTF-8");
  final HttpClient httpclient = new HttpClient();
  RequestEntity entity = new StringRequestEntity(soapEnvelope, "application/x-www-form-urlencoded", null);
  postMethod.setRequestEntity(entity);
  try {

    try {
      System.out.println("URI: " + postMethod.getURI());
      final int result = httpclient.executeMethod(postMethod);
      System.out.println("Response code: " + result);
      return postMethod.getResponseBodyAsString();
    } catch (Exception exception) {
      System.err.println(exception);
    }
  } finally {
    postMethod.releaseConnection();
  }

  return null;
}
 
Example 24
Project: teamcity-s3-artifact-storage-plugin   File: S3ArtifactsPublisher.java   Source Code and License 6 votes vote down vote up
@NotNull
private static Map<String, URL> resolveUploadUrls(AgentRunningBuild build, @NotNull Collection<String> s3ObjectKeys) throws IOException {
  BuildAgentConfiguration agentConfiguration = build.getAgentConfiguration();
  String targetUrl = agentConfiguration.getServerUrl() + HTTP_AUTH + ARTEFACTS_S3_UPLOAD_PRESIGN_URLS_HTML;
  int connectionTimeout = agentConfiguration.getServerConnectionTimeout();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(build.getAccessUser(), build.getAccessCode());
  HttpClient httpClient = HttpUtil.createHttpClient(connectionTimeout, new URL(targetUrl), credentials);
  PostMethod post = new PostMethod(targetUrl);
  post.setRequestEntity(new StringRequestEntity(S3PreSignUrlHelper.writeS3ObjectKeys(s3ObjectKeys), APPLICATION_XML, UTF_8));
  post.setDoAuthentication(true);
  int responseCode = httpClient.executeMethod(post);
  if(responseCode != 200){
    LOG.debug("Failed resolving S3 pre-signed URL for build " + build.describe(false) + " . Response code " + responseCode);
    return Collections.emptyMap();
  }
  return S3PreSignUrlHelper.readPreSignUrlMapping(post.getResponseBodyAsString());
}
 
Example 25
Project: cashion   File: UserValidate.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    HttpClient hc = new HttpClient();
        PostMethod method = null;
        //同步企业名录
        method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/UserValidate.htm");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "pancs_qd");
        jsonObject.put("password", "123456");
        String transJson = jsonObject.toString();
        RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8");
        method.setRequestEntity(se);
        //使用系统提供的默认的恢复策略
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        //设置超时的时间
        method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000);	            
        int statusCode = hc.executeMethod(method);
        System.out.println(statusCode);
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));
        System.out.println("getStatusLine:"+method.getStatusLine());
        String response = new String(method.getResponseBodyAsString().getBytes("utf-8"));
        System.out.println("response:"+response);
}
 
Example 26
Project: cashion   File: allBPOInterface.java   Source Code and License 6 votes vote down vote up
public void getCustomerList()  throws JSONException, IOException {
    HttpClient hc = new HttpClient();
    PostMethod method = null;
    JSONObject jsonObject = new JSONObject();
    System.out.println("同步企业名录");
    method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/getCustomerList.htm");
    jsonObject.put("lastSyncDate", "201501");
    String transJson = jsonObject.toString();
    RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8");
    method.setRequestEntity(se);
    //使用系统提供的默认的恢复策略
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    //设置超时的时间
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000);
    hc.executeMethod(method);
    InputStream strStream = method.getResponseBodyAsStream();
    ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
    int   i=-1; 
    while((i=strStream.read())!=-1){ 
    baos.write(i); 
    } 
   String strBody =   baos.toString(); 
    System.out.println(new String(strBody));
    System.out.println("getStatusLine:"+method.getStatusLine());
}
 
Example 27
Project: cashion   File: allBPOInterface.java   Source Code and License 6 votes vote down vote up
public void UserValidate() throws JSONException, IOException {
    HttpClient hc = new HttpClient();
    PostMethod method = null;
    System.out.println(" 扫描前置客户端权限校验");
    method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/UserValidate.htm");
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("username", "pancs_qd");
    jsonObject.put("password", "111111");
    String transJson = jsonObject.toString();
    RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8");
    method.setRequestEntity(se);
    //使用系统提供的默认的恢复策略
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    //设置超时的时间
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000);	            
    hc.executeMethod(method);
    InputStream strStream = method.getResponseBodyAsStream();
    ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
    int   i=-1; 
    while((i=strStream.read())!=-1){ 
    baos.write(i); 
    } 
   String strBody =   baos.toString(); 
    System.out.println(new String(strBody));
    System.out.println("getStatusLine:"+method.getStatusLine());
}
 
Example 28
Project: cashion   File: getCustomerList.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
      HttpClient hc = new HttpClient();
          PostMethod method = null;
          JSONObject jsonObject = new JSONObject();
          //同步企业名录
          method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/getCustomerList.htm");
          jsonObject.put("lastSyncDate", "201501");
          String transJson = jsonObject.toString();
          RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8");
          method.setRequestEntity(se);
          //使用系统提供的默认的恢复策略
          method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
          //设置超时的时间
          method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000);
          int statusCode = hc.executeMethod(method);
          System.out.println(statusCode);
          byte[] responseBody = method.getResponseBody();
          System.out.println(new String(responseBody));
          System.out.println("getStatusLine:"+method.getStatusLine());
          String response = new String(method.getResponseBodyAsString().getBytes("utf-8"));
          System.out.println("response:"+response);
}
 
Example 29
Project: product-ei   File: ESBJAVA2615TestCase.java   Source Code and License 6 votes vote down vote up
private String httpClient(String proxyLocation, String xml) {
    try {
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(proxyLocation);

        post.setRequestEntity(new StringRequestEntity(xml));
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.setRequestHeader("SOAPAction", "urn:mediate");
        httpclient.executeMethod(post);

        InputStream in = post.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append("\n");
        }
        reader.close();
        return buffer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 30
Project: product-ei   File: ESBJAVA4846HttpProtocolVersionTestCase.java   Source Code and License 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message")
public void sendingHTTP10Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_0);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched");

}
 
Example 31
Project: product-ei   File: ESBJAVA4846HttpProtocolVersionTestCase.java   Source Code and License 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
 
Example 32
Project: intellij-ce-playground   File: JiraIntegrationTest.java   Source Code and License 6 votes vote down vote up
private String createIssueViaRestApi(@NotNull String project, @NotNull String summary) throws Exception {
  final HttpClient client = myRepository.getHttpClient();
  final PostMethod method = new PostMethod(myRepository.getUrl() + "/rest/api/latest/issue");
  try {
    // For simplicity assume that project, summary and username don't contain illegal characters
    @Language("JSON")
    final String json = "{\"fields\": {\n" +
                        "  \"project\": {\n" +
                        "    \"key\": \"" + project + "\"\n" +
                        "  },\n" +
                        "  \"issuetype\": {\n" +
                        "    \"name\": \"Bug\"\n" +
                        "  },\n" +
                        "  \"assignee\": {\n" +
                        "    \"name\": \"" + myRepository.getUsername() + "\"\n" +
                        "  },\n" +
                        "  \"summary\": \"" + summary + "\"\n" +
                        "}}";
    method.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
    client.executeMethod(method);
    return new Gson().fromJson(method.getResponseBodyAsString(), JsonObject.class).get("id").getAsString();
  }
  finally {
    method.releaseConnection();
  }
}
 
Example 33
Project: build-notifications-plugin   File: BotecoMessage.java   Source Code and License 6 votes vote down vote up
@Override
public void send() {
  HttpClient client = new HttpClient();
  PostMethod post = new PostMethod(endpoint);
  post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  Map<String, String> values = new HashMap<String, String>();
  values.put("title", title);
  values.put("text", content + "\n\n" + extraMessage);
  values.put("url", url);
  values.put("priority", priority);
  try {
    post.setRequestEntity(new StringRequestEntity(JSONObject.fromObject(values).toString(),
        "application/json", "UTF-8"));
    client.executeMethod(post);
  } catch (IOException e) {
    LOGGER.severe("Error while sending notification: " + e.getMessage());
    e.printStackTrace();
  }
}
 
Example 34
Project: HareDBWebRESTful   File: HareSparkResourceTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception{
	checkLocalJarFile();
	checkSparkAssemblyJar();
	
	clusterConfiguration = HareSparkResourceTest.class.getResource("/hadoopConf").getPath();
	
	PostMethod method = new PostMethod(httpUrlRoot + "/usersession");
	String json = HareSparkResourceTest.objectToJsonStr(HareSparkResourceTest.getUserSession());
	
	StringRequestEntity requestEntity = new StringRequestEntity(json, contentType, charSet);
	method.setRequestEntity(requestEntity);
		
	int statusCode = client.executeMethod(method);
	assertEquals(200, statusCode);//test create session
}
 
Example 35
Project: HareDBWebRESTful   File: HareSparkResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAlterTable() throws Exception{
	testCreateTable();
	String tableName = "testtable";

	PostMethod method = new PostMethod(httpUrlRoot + "/altertable");
	AlterTableBean alterTableBean = new AlterTableBean();
	alterTableBean.setTablename(tableName);
	alterTableBean.setColumnNames(Arrays.asList("col1", "col2"));
	alterTableBean.setDataTypes(Arrays.asList("string", "string"));
	
	String json = HareSparkResourceTest.objectToJsonStr(alterTableBean);
	
	StringRequestEntity requestEntity = new StringRequestEntity(json, contentType, charSet);
	method.setRequestEntity(requestEntity);
	int status = client.executeMethod(method);
	assertEquals(200, status);
	
	byte[] resultByte = method.getResponseBody(1024 * 1024 * 10);
	String result = new String(resultByte);
	
	Gson gson = new Gson();
	ResponseInfoBean response = gson.fromJson(result, ResponseInfoBean.class);
	assertEquals("success", response.getStatus());
}
 
Example 36
Project: HareDBWebRESTful   File: HareSparkResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testUploadDataFileStatus() throws Exception{
	String jobName = this.uploadFile("uploadTable");
	
	PostMethod method = new PostMethod(httpUrlRoot + "/uploaddatafile/status");
	UploadDataFileStatusBean uploadDataFileStatusBean = new UploadDataFileStatusBean();
	uploadDataFileStatusBean.setUploadJobName(jobName);
	
	String json = HareSparkResourceTest.objectToJsonStr(uploadDataFileStatusBean);
	
	StringRequestEntity requestEntity = new StringRequestEntity(json, contentType, charSet);
	method.setRequestEntity(requestEntity);
	client.executeMethod(method);
	
	byte[] resultByte = method.getResponseBody(1024 * 1024 * 20);
	String result = new String(resultByte);
	
	Gson gson = new Gson();
	UploadDataFileStatusResponseBean response = gson.fromJson(result, UploadDataFileStatusResponseBean.class);
	assertEquals(response.getStatus(), "success");
	assertTrue(response.getException() == null);
}
 
Example 37
Project: HareDBWebRESTful   File: HareSparkResourceTest.java   Source Code and License 6 votes vote down vote up
@Ignore
@Test
public void testQueryStatus() throws Exception{
	PostMethod method = new PostMethod(httpUrlRoot + "/querystatus");
	QueryStatusBean queryStatusBean = new QueryStatusBean();
	//TODO set appliationName
	
	String json = HareSparkResourceTest.objectToJsonStr(queryStatusBean);
	
	StringRequestEntity requestEntity = new StringRequestEntity(json, contentType, charSet);
	method.setRequestEntity(requestEntity);
	client.executeMethod(method);
	
	byte[] resultByte = method.getResponseBody(1024 * 1024 * 10);
	String result = new String(resultByte);
	
	Gson gson = new Gson();
	QueryStatusResponseBean response = gson.fromJson(result, QueryStatusResponseBean.class);
	response.getJobStatus();
}
 
Example 38
Project: HareDBWebRESTful   File: HareSparkResourceTest.java   Source Code and License 6 votes vote down vote up
private ResponseInfoBean createTable(String tableName) throws Exception{
	PostMethod method = new PostMethod(httpUrlRoot + "/createtable");
	CreateTableBean createTableBean = new CreateTableBean();
	createTableBean.setTablename(tableName);
	createTableBean.setColumnNames(Arrays.asList("col1", "col2", "col3", "col4"));
	createTableBean.setDataTypes(Arrays.asList("string", "string", "string", "string"));
	
	String json = HareSparkResourceTest.objectToJsonStr(createTableBean);
	StringRequestEntity requestEntity = new StringRequestEntity(json, contentType, charSet);
	method.setRequestEntity(requestEntity);
	client.executeMethod(method);
	byte[] resultByte = method.getResponseBody(1024 * 1024 * 10);
	String result = new String(resultByte);
	
	Gson gson = new Gson();
	return gson.fromJson(result, ResponseInfoBean.class);
}
 
Example 39
Project: HareDBWebRESTful   File: HareSparkResourceTest.java   Source Code and License 6 votes vote down vote up
private DescribeTableResponseBean tableDescribe(String tableName) throws Exception{
	PostMethod method = new PostMethod(httpUrlRoot + "/describetable");
	DescribeTableBean describeTableBean = new DescribeTableBean();
	describeTableBean.setTablename(tableName);
	String json = HareSparkResourceTest.objectToJsonStr(describeTableBean);

	StringRequestEntity requestEntity = new StringRequestEntity(json, contentType, charSet);
	method.setRequestEntity(requestEntity);
	
	int statusCode = client.executeMethod(method);
	assertEquals(200, statusCode);
	
	byte[] resultByte = method.getResponseBody(1024 * 1024 *10);
	String result = new String(resultByte);
	
	Gson gson = new Gson();
	return gson.fromJson(result, DescribeTableResponseBean.class);
}
 
Example 40
Project: HareDBWebRESTful   File: HareSparkResourceTest.java   Source Code and License 6 votes vote down vote up
private boolean isExists(String tableName) throws Exception{
	PostMethod method = new PostMethod(httpUrlRoot + "/isExists");
	
	StringRequestEntity requestEntity = new StringRequestEntity(tableName, contentType, charSet);
	method.setRequestEntity(requestEntity);
	client.executeMethod(method);
	byte[] resultByte = method.getResponseBody(1024 * 1024 * 10);
	String result = new String(resultByte);
	
	Gson gson = new Gson();
	if(gson.fromJson(result, String.class).equals("true")){
		return true;
	}else{
		return false;
	}
}
 
Example 41
Project: realtime-analytics   File: Simulator.java   Source Code and License 6 votes vote down vote up
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException,
            JsonMappingException, UnsupportedEncodingException, HttpException {
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> m = new HashMap<String, Object>();

        m.put("si", "12345");
        m.put("ct", System.currentTimeMillis());
        
        String payload = mapper.writeValueAsString(m);
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent");
//      method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8"));
        int status = client.executeMethod(method);
        System.out.println(Arrays.toString(method.getResponseHeaders()));
        System.out.println("Status code: " + status + ", Body: " +  method.getResponseBodyAsString());
    }
 
Example 42
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testUpdateCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setKey(g1.getKey());
    vo.setName("rest-g1-mod");
    vo.setDescription("rest-g1 description");
    vo.setMinParticipants(g1.getMinParticipants());
    vo.setMaxParticipants(g1.getMaxParticipants());
    vo.setType(g1.getType());

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals(bg.getName(), "rest-g1-mod");
    assertEquals(bg.getDescription(), "rest-g1 description");
}
 
Example 43
Project: olat   File: CourseGroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testBasicSecurityPutCall() throws IOException {
    final HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8");

    final GroupVO vo = new GroupVO();
    vo.setName("hello dont put");
    vo.setDescription("hello description dont put");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);

    assertEquals(401, code);
}
 
Example 44
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testUpdateCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setKey(g1.getKey());
    vo.setName("rest-g1-mod");
    vo.setDescription("rest-g1 description");
    vo.setMinParticipants(g1.getMinParticipants());
    vo.setMaxParticipants(g1.getMaxParticipants());
    vo.setType(g1.getType());

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals(bg.getName(), "rest-g1-mod");
    assertEquals(bg.getDescription(), "rest-g1 description");
}
 
Example 45
Project: olat   File: CourseGroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testBasicSecurityPutCall() throws IOException {
    final HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8");

    final GroupVO vo = new GroupVO();
    vo.setName("hello dont put");
    vo.setDescription("hello description dont put");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);

    assertEquals(401, code);
}
 
Example 46
Project: openshift-acmeair   File: AcmeAirTest.java   Source Code and License 6 votes vote down vote up
private Customer updateCustomer(String id, Cookie sessionCookie, Customer customer) throws Exception {
    PostMethod method = new PostMethod(baseURL + "/rest/api/customer/byid/" + id);
    method.setRequestHeader("Cookie", sessionCookie.toExternalForm());
    
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(customer);
    StringRequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
    method.setRequestEntity(requestEntity);
    
    try {
        int statusCode = client.executeMethod(method);
        assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);
        String response = method.getResponseBodyAsString();
        Customer c = mapper.readValue(response, Customer.class);
        return c;
    } finally {
        method.releaseConnection();
    }
}
 
Example 47
Project: community-edition-old   File: PublicApiHttpClient.java   Source Code and License 6 votes vote down vote up
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
            final String relationCollectionName, final Object relationshipEntityId, final String body, String contentType) throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
                relationshipEntityId, null);
    String url = endpoint.getUrl();

    PostMethod req = new PostMethod(url.toString());
    if (body != null)
    {
        if (contentType == null || contentType.isEmpty())
        {
            contentType = "application/json";
        }
        StringRequestEntity requestEntity = new StringRequestEntity(body, contentType, "UTF-8");
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example 48
Project: modules   File: IHETemplateServiceImpl.java   Source Code and License 6 votes vote down vote up
private void sendTemplate(String url, String template, Credentials credentials) throws IOException {

        PostMethod post = new PostMethod(url);
        HttpClient client = new HttpClient();

        post.setRequestEntity(new StringRequestEntity(template, "application/xml", "utf-8"));

        if (credentials != null) {
            client.getParams().setAuthenticationPreemptive(true);
            client.getState().setCredentials(AuthScope.ANY, credentials);
        }

        LOGGER.info("Sending template to URL: {}", post.getURI().toString());
        int responseCode = client.executeMethod(post);
        LOGGER.info("Response code: {}", responseCode);
    }
 
Example 49
Project: modules   File: SmsHttpService.java   Source Code and License 6 votes vote down vote up
private static String printableMethodParams(HttpMethod method) {
    if (method.getClass().equals(PostMethod.class)) {
        PostMethod postMethod = (PostMethod) method;
        RequestEntity requestEntity = postMethod.getRequestEntity();
        if (MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(requestEntity.getContentType())) {
            StringBuilder sb = new StringBuilder();
            NameValuePair[] params = postMethod.getParameters();
            for (NameValuePair param : params) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append(String.format("%s: %s", param.getName(), param.getValue()));
            }
            return "POST Parameters: " + sb.toString();
        } else if (requestEntity.getClass() == StringRequestEntity.class) {
            // Assume MediaType.APPLICATION_JSON_VALUE
            return "POST JSON: " + ((StringRequestEntity) requestEntity).getContent();
        }
    } else if (method.getClass().equals(GetMethod.class)) {
        GetMethod g = (GetMethod) method;
        return String.format("GET QueryString: %s", g.getQueryString());
    }

    throw new IllegalStateException(String.format("Unexpected HTTP method: %s", method.getClass()));
}
 
Example 50
Project: testrail-jenkins-plugin   File: TestRailClient.java   Source Code and License 6 votes vote down vote up
private TestRailResponse httpPostInt(String path, String payload)
        throws UnsupportedEncodingException, IOException, HTTPException {
    TestRailResponse result;
    PostMethod post = new PostMethod(host + "/" + path);
    HttpClient httpclient = setUpHttpClient(post);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(
                payload,
                "application/json",
                "UTF-8"
        );
        post.setRequestEntity(requestEntity);
        Integer status = httpclient.executeMethod(post);
        String body = new String(post.getResponseBody(), post.getResponseCharSet());
        result = new TestRailResponse(status, body);
    } finally {
        post.releaseConnection();
    }

    return result;
}
 
Example 51
Project: DotCi-Plugins-Starter-Pack   File: WebhookNotifier.java   Source Code and License 6 votes vote down vote up
@Override
protected boolean notify(DynamicBuild build, BuildListener listener) {
    Map<String, ?> options = (Map<String, ?>) getOptions();
    HttpClient client = getHttpClient();
    String requestUrl = (String) options.get("url");
    PostMethod post = new PostMethod(requestUrl);

    Map<String, String> payload = (Map<String, String>) options.get("payload");
    ObjectMapper objectMapper = new ObjectMapper();

    try {
        String payloadJson = objectMapper.writeValueAsString(payload);
        StringRequestEntity requestEntity = new StringRequestEntity(payloadJson, "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);
        int statusCode = client.executeMethod(post);
        listener.getLogger().println("Posted Paylod " + payloadJson + " to " + requestUrl + " with response code " + statusCode);
    } catch (Exception e) {
        listener.getLogger().print("Failed to make a POST to webhook. Check Jenkins logs for exceptions.");
        LOGGER.log(Level.WARNING, "Error posting to webhook", e);
        return false;
    } finally {
        post.releaseConnection();
    }
    return false;
}
 
Example 52
Project: cloudstack   File: BigSwitchBcfApi.java   Source Code and License 6 votes vote down vote up
protected <T> String executeUpdateObject(final T newObject, final String uri,
        final Map<String, String> parameters) throws BigSwitchBcfApiException,
IllegalArgumentException{
    checkInvariants();

    PutMethod pm = (PutMethod)createMethod("put", uri, _port);

    setHttpHeader(pm);

    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null));
    } catch (UnsupportedEncodingException e) {
        throw new BigSwitchBcfApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    String hash = checkResponse(pm, "BigSwitch HTTP update failed: ");

    pm.releaseConnection();

    return hash;
}
 
Example 53
Project: po-mylyn-integration   File: ProjectOpenHttpClient.java   Source Code and License 6 votes vote down vote up
public String executePost(String url, String body, Map<String, String> parameters,
		IProgressMonitor monitor) throws ProjectOpenException {
	PostMethod postRequest = new PostMethod(ProjectOpenUtil.stripSlash(location.getUrl())
			+ url);
	
	try {
		postRequest.setRequestEntity(new StringRequestEntity(body, "text/xml", "UTF-8"));
	} catch (UnsupportedEncodingException e) {
		throw new RuntimeException(e);
	}

	for (String key : parameters.keySet()) {
		postRequest.setParameter(key, parameters.get(key));
	}

	return executeMethod(postRequest, monitor);
}
 
Example 54
Project: httpclient3-ntml   File: TestMethodCharEncoding.java   Source Code and License 6 votes vote down vote up
public void testRussianInRequestBody() throws IOException {
    PostMethod httppost = new PostMethod("/");
    String s = constructString(RUSSIAN_STUFF_UNICODE);
    // Test UTF-8 encoding
    httppost.setRequestEntity(
        new StringRequestEntity(s, "text/plain", CHARSET_UTF8));
    verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_UTF8);
    // Test KOI8-R
    httppost.setRequestEntity(
        new StringRequestEntity(s, "text/plain", CHARSET_KOI8_R));
    verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_KOI8R);
    // Test WIN1251
    httppost.setRequestEntity(
        new StringRequestEntity(s, "text/plain", CHARSET_WIN1251));
    verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_WIN1251);
}
 
Example 55
Project: httpclient3-ntml   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + host auth + connection keep-alive 
 */
public void testPostHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 56
Project: httpclient3-ntml   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + host auth + connection close 
 */
public void testPostHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 57
Project: httpclient3-ntml   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + invalid host auth 
 */
public void testPostHostInvalidAuth() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.client.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("testuser", "wrongstuff"));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode());
    } finally {
        post.releaseConnection();
    }
}
 
Example 58
Project: httpclient3-ntml   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive 
 */
public void testPostInteractiveHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 59
Project: httpclient3-ntml   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection close 
 */
public void testPostInteractiveHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
            
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 60
Project: httpclient3-ntml   File: TestProxy.java   Source Code and License 6 votes vote down vote up
/**
 * Tests POST via authenticating proxy
 */
public void testPostAuthProxy() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.server.setHttpService(new FeedbackService());

    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}