org.apache.commons.httpclient.methods.ByteArrayRequestEntity Java Examples

The following examples show how to use org.apache.commons.httpclient.methods.ByteArrayRequestEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected PutMethod internalCreateOrUpdate(String encodedHref, byte[] mimeContent) throws IOException {
    PutMethod putmethod = new PutMethod(encodedHref);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Overwrite", "f");
    if (etag != null) {
        putmethod.setRequestHeader("If-Match", etag);
    }
    if (noneMatch != null) {
        putmethod.setRequestHeader("If-None-Match", noneMatch);
    }
    putmethod.setRequestHeader("Content-Type", "message/rfc822");
    putmethod.setRequestEntity(new ByteArrayRequestEntity(mimeContent, "message/rfc822"));
    try {
        httpClient.executeMethod(putmethod);
    } finally {
        putmethod.releaseConnection();
    }
    return putmethod;
}
 
Example #2
Source File: HttpSOAPClient.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates the request entity that makes up the POST message body.
 * 
 * @param message message to be sent
 * @param charset character set used for the message
 * 
 * @return request entity that makes up the POST message body
 * 
 * @throws SOAPClientException thrown if the message could not be marshalled
 */
protected RequestEntity createRequestEntity(Envelope message, Charset charset) throws SOAPClientException {
    try {
        Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message);
        ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(arrayOut, charset);

        if (log.isDebugEnabled()) {
            log.debug("Outbound SOAP message is:\n" + XMLHelper.prettyPrintXML(marshaller.marshall(message)));
        }
        XMLHelper.writeNode(marshaller.marshall(message), writer);
        return new ByteArrayRequestEntity(arrayOut.toByteArray(), "text/xml");
    } catch (MarshallingException e) {
        throw new SOAPClientException("Unable to marshall SOAP envelope", e);
    }
}
 
Example #3
Source File: PublicApiHttpClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 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 byte[] 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/octet-stream";
        }
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(body, contentType);
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example #4
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void sendRequest() throws IOException {
  synchronized(lock) {
    if (out != null) {
      if (!(resCache instanceof EntityEnclosingMethod)) {
        System.err.println("Warning: data written to request's body, "
                           +"but not supported");
      } else {
        EntityEnclosingMethod m = (EntityEnclosingMethod) resCache;
        m.setRequestEntity(new ByteArrayRequestEntity(out.getBytes()));
      }
    }

    client.executeMethod(resCache);
    requestSent = true;
  }
}
 
Example #5
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 处理Put请求
 * @param url
 * @param headers
 * @param object
 * @param property
 * @return
 */
public static JSONObject doPut(String url, Map<String, String> headers,String jsonString) {

	HttpClient httpClient = new HttpClient();
	
	PutMethod putMethod = new PutMethod(url);
	
	//设置header
	setHeaders(putMethod,headers);
	
	//设置put传递的json数据
	if(jsonString!=null&&!"".equals(jsonString)){
		putMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes()));
	}
	
	String responseStr = "";
	
	try {
		httpClient.executeMethod(putMethod);
		responseStr = putMethod.getResponseBodyAsString();
	} catch (Exception e) {
		log.error(e);
		responseStr="{status:0}";
	} 
	return JSONObject.parseObject(responseStr);
}
 
Example #6
Source File: AbstractSubmarineServerTest.java    From submarine with Apache License 2.0 5 votes vote down vote up
protected static PutMethod httpPut(String path, String body, String user, String pwd) throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PutMethod putMethod = new PutMethod(URL + path);
  putMethod.addRequestHeader("Origin", URL);
  putMethod.setRequestHeader("Content-type", "application/yaml");
  RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
  putMethod.setRequestEntity(entity);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    putMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(putMethod);
  LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText());
  return putMethod;
}
 
Example #7
Source File: SOLRAPIClientTest.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setRequestAuthentication(HttpMethod method, byte[] message) throws IOException
{
    if (method instanceof PostMethod)
    {
        // encrypt body
        Pair<byte[], AlgorithmParameters> encrypted = encryptor.encrypt(KeyProvider.ALIAS_SOLR, null, message);
        setRequestAlgorithmParameters(method, encrypted.getSecond());

        ((PostMethod) method).setRequestEntity(new ByteArrayRequestEntity(encrypted.getFirst(), "application/octet-stream"));
    }

    long requestTimestamp = System.currentTimeMillis();

    // add MAC header
    byte[] mac = macUtils.generateMAC(KeyProvider.ALIAS_SOLR, new MACInput(message, requestTimestamp, getLocalIPAddress()));

    if (logger.isDebugEnabled())
    {
        logger.debug("Setting MAC " + mac + " on HTTP request " + method.getPath());
        logger.debug("Setting timestamp " + requestTimestamp + " on HTTP request " + method.getPath());
    }

    if (overrideMAC)
    {
        mac[0] += (byte) 1;
    }
    setRequestMac(method, mac);

    if (overrideTimestamp)
    {
        requestTimestamp += 60000;
    }
    // prevent replays
    setRequestTimestamp(method, requestTimestamp);
}
 
Example #8
Source File: CloudMetadataScanner.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private static HttpMethod createRequestMethod(
        HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException {
    HttpMethod httpMethod = new ZapGetMethod();
    httpMethod.setURI(header.getURI());
    httpMethod.setParams(params);
    params.setVersion(HttpVersion.HTTP_1_1);

    String msg = header.getHeadersAsString();

    String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg);
    String token = null;
    String name = null;
    String value = null;

    int pos = 0;
    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);
    }
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
 
Example #9
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 处理Post请求
 * @param url
 * @param params post请求参数
 * @param jsonString post传递json数据
 * @return
 * @throws HttpException
 * @throws IOException
 */
public static JSONObject doPost(String url,Map<String,String> headers,Map<String,String> params,String jsonString) {
	
	HttpClient client = new HttpClient();
	//post请求
	PostMethod postMethod = new PostMethod(url);
	
	//设置header
	setHeaders(postMethod,headers);
	
	//设置post请求参数
	setParams(postMethod,params);
	
	//设置post传递的json数据
	if(jsonString!=null&&!"".equals(jsonString)){
		postMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes()));
	}
	
	String responseStr = "";
	
	try {
		client.executeMethod(postMethod);
		responseStr = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		log.error(e);
		e.printStackTrace();
		responseStr="{status:0}";
	} 
	
	return JSONObject.parseObject(responseStr);
	
}
 
Example #10
Source File: AbstractTestRestApi.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
protected static PutMethod httpPut(String path, String body, String user, String pwd)
        throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PutMethod putMethod = new PutMethod(URL + path);
  putMethod.addRequestHeader("Origin", URL);
  RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
  putMethod.setRequestEntity(entity);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    putMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(putMethod);
  LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText());
  return putMethod;
}
 
Example #11
Source File: ZeppelinServerMock.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
protected static PutMethod httpPut(String path, String body, String user, String pwd)
    throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PutMethod putMethod = new PutMethod(URL + path);
  putMethod.addRequestHeader("Origin", URL);
  RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
  putMethod.setRequestEntity(entity);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    putMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(putMethod);
  LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText());
  return putMethod;
}
 
Example #12
Source File: VmRuntimeJettyKitchenSink2Test.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the deferredTask handler is installed.
 */
public void testDeferredTask() throws Exception {
  // Replace the API proxy delegate so we can fake API responses.
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);

  // Add a api response so the task queue api is happy.
  TaskQueueBulkAddResponse taskAddResponse = new TaskQueueBulkAddResponse();
  TaskResult taskResult = taskAddResponse.addTaskResult();
  taskResult.setResult(ErrorCode.OK.getValue());
  taskResult.setChosenTaskName("abc");
  fakeApiProxy.addApiResponse(taskAddResponse);

  // Issue a deferredTaskRequest with payload.
  String testData = "0987654321acbdefghijklmn";
  String[] lines = fetchUrl(createUrl("/testTaskQueue?deferredTask=1&deferredData=" + testData));
  TaskQueueBulkAddRequest request = new TaskQueueBulkAddRequest();
  request.parseFrom(fakeApiProxy.getLastRequest().requestData);
  assertEquals(1, request.addRequestSize());
  TaskQueueAddRequest addRequest = request.getAddRequest(0);
  assertEquals(TaskQueueAddRequest.RequestMethod.POST.getValue(), addRequest.getMethod());

  // Pull out the request and fire it at the app.
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  PostMethod post = new PostMethod(createUrl(addRequest.getUrl()).toString());
  post.getParams().setVersion(HttpVersion.HTTP_1_0);
  // Add the required Task queue header, plus any headers from the request.
  post.addRequestHeader("X-AppEngine-QueueName", "1");
  for (TaskQueueAddRequest.Header header : addRequest.headers()) {
    post.addRequestHeader(header.getKey(), header.getValue());
  }
  post.setRequestEntity(new ByteArrayRequestEntity(addRequest.getBodyAsBytes()));
  int httpCode = httpClient.executeMethod(post);
  assertEquals(HttpURLConnection.HTTP_OK, httpCode);

  // Verify that the task was handled and that the payload is correct.
  lines = fetchUrl(createUrl("/testTaskQueue?getLastPost=1"));
  assertEquals("deferredData:" + testData, lines[lines.length - 1]);
}
 
Example #13
Source File: HttpClient3EntityExtractor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String getEntity(HttpMethod httpMethod) {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            try {
                String entityValue;
                String charSet = entityEnclosingMethod.getRequestCharSet();
                if (StringUtils.isEmpty(charSet)) {
                    charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                }
                if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
                    entityValue = entityUtilsToString(entity, charSet);
                } else {
                    entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                }
                return entityValue;
            } catch (Exception e) {
                if (isDebug) {
                    logger.debug("Failed to get entity. httpMethod={}", httpMethod, e);
                }
            }
        }
    }
    return null;
}
 
Example #14
Source File: RemoteConnectorRequestImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setRequestBody(byte[] body)
{
    requestBody = new ByteArrayRequestEntity(body);
}
 
Example #15
Source File: AbstractHttpClient.java    From alfresco-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected HttpMethod createMethod(Request req) throws IOException
{
    StringBuilder url = new StringBuilder(128);
    url.append(baseUrl);
    url.append("/service/");
    url.append(req.getFullUri());

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if(method.equalsIgnoreCase("GET"))
    {
        GetMethod get = new GetMethod(url.toString());
        httpMethod = get;
        httpMethod.setFollowRedirects(true);
    }
    else if(method.equalsIgnoreCase("POST"))
    {
        PostMethod post = new PostMethod(url.toString());
        httpMethod = post;
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(req.getBody(), req.getType());
        if (req.getBody().length > DEFAULT_SAVEPOST_BUFFER)
        {
            post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        }
        post.setRequestEntity(requestEntity);
        // Note: not able to automatically follow redirects for POST, this is handled by sendRemoteRequest
    }
    else if(method.equalsIgnoreCase("HEAD"))
    {
        HeadMethod head = new HeadMethod(url.toString());
        httpMethod = head;
        httpMethod.setFollowRedirects(true);
    }
    else
    {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }

    if (req.getHeaders() != null)
    {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet())
        {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }
    
    return httpMethod;
}
 
Example #16
Source File: HttpResponse.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public String toString()
{
	StringBuilder sb = new StringBuilder();

	String requestType = null;
       RequestEntity requestEntity = null;

	if (method instanceof GetMethod)
	{
		requestType = "GET";
	}
       else if (method instanceof PutMethod)
       {
           requestType = "PUT";
           requestEntity = ((PutMethod) method).getRequestEntity();
       }
       else if (method instanceof PostMethod)
	{
		requestType = "POST";
           requestEntity = ((PostMethod)method).getRequestEntity();
	}
	else if (method instanceof DeleteMethod)
	{
		requestType = "DELETE";
	}

	try
	{
		sb.append(requestType).append(" request ").append(method.getURI()).append("\n");
	}
	catch (URIException e)
	{
	}

       if (requestEntity != null)
       {
           sb.append("\nRequest body: ");
           if (requestEntity instanceof StringRequestEntity)
           {
               sb.append(((StringRequestEntity)requestEntity).getContent());
           }
           else if (requestEntity instanceof ByteArrayRequestEntity)
           {
               sb.append(" << ").append(((ByteArrayRequestEntity)requestEntity).getContent().length).append(" bytes >>");
           }
           sb.append("\n");
       }

	sb.append("user ").append(user).append("\n");
	sb.append("returned ").append(method.getStatusCode()).append(" and took ").append(time).append("ms").append("\n");

       String contentType = null;
       Header hdr = method.getResponseHeader("Content-Type");
       if (hdr != null)
       {
           contentType = hdr.getValue();
       }
       sb.append("Response content type: ").append(contentType).append("\n");

       if (contentType != null)
       {
           sb.append("\nResponse body: ");
           if (contentType.startsWith("text/plain") || contentType.startsWith("application/json"))
           {
               sb.append(getResponse());
               sb.append("\n");
           }
           else if(getResponseAsBytes() != null)
           {
               sb.append(" << ").append(getResponseAsBytes().length).append(" bytes >>");
               sb.append("\n");
           }
       }

	return sb.toString();
}