类org.apache.commons.httpclient.methods.ByteArrayRequestEntity源码实例Demo

下面列出了怎么用org.apache.commons.httpclient.methods.ByteArrayRequestEntity的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: davmail   文件: DavExchangeSession.java
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;
}
 
源代码2 项目: lams   文件: HttpSOAPClient.java
/**
 * 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);
    }
}
 
源代码3 项目: alfresco-remote-api   文件: PublicApiHttpClient.java
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);
}
 
源代码4 项目: knopflerfish.org   文件: HttpClientConnection.java
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;
  }
}
 
源代码5 项目: Java-sdk   文件: HttpUtils.java
/**
 * 处理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);
}
 
源代码6 项目: submarine   文件: AbstractSubmarineServerTest.java
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;
}
 
源代码7 项目: SearchServices   文件: SOLRAPIClientTest.java
@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);
}
 
源代码8 项目: zap-extensions   文件: CloudMetadataScanner.java
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;
}
 
源代码9 项目: Java-sdk   文件: HttpUtils.java
/**
 * 处理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);
	
}
 
源代码10 项目: zeppelin   文件: AbstractTestRestApi.java
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;
}
 
源代码11 项目: zeppelin   文件: ZeppelinServerMock.java
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;
}
 
/**
 * 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]);
}
 
源代码13 项目: pinpoint   文件: HttpClient3EntityExtractor.java
@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;
}
 
public void setRequestBody(byte[] body)
{
    requestBody = new ByteArrayRequestEntity(body);
}
 
源代码15 项目: alfresco-core   文件: AbstractHttpClient.java
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;
}
 
源代码16 项目: alfresco-remote-api   文件: HttpResponse.java
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();
}
 
 类方法
 同包方法