Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java

public void executeDDL(String str, String url) throws Exception {
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(str));
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    executeHttpMethod(method);/*from  w w w.  j ava 2s .c o m*/
}

From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java

public void executeUpdate(String str, String url) throws Exception {
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(str));

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    executeHttpMethod(method);//  www .j  a  v  a2 s .com
}

From source file:eu.learnpad.core.impl.qm.XwikiBridgeInterfaceRestResource.java

private String localGenerateQuestionnaires(String modelSetId, String type, byte[] configurationFile)
        throws LpRestExceptionXWikiImpl {
    // Ask the QM to generate new questionnaire for a given model set
    // that has been already imported
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/qm/bridge/generate/%s", DefaultRestResource.REST_URI, modelSetId);
    PostMethod postMethod = new PostMethod(uri);

    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type);
    postMethod.setQueryString(queryString);

    RequestEntity requestEntity = null;// w  w  w .  ja va2 s  . com
    if (configurationFile != null) {
        postMethod.addRequestHeader("Content-Type", "application/octet-stream");
        requestEntity = new ByteArrayRequestEntity(configurationFile);
    }
    postMethod.setRequestEntity(requestEntity);

    String genProcessID = null;
    try {
        httpClient.executeMethod(postMethod);
        genProcessID = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
    return genProcessID;
}

From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSink2Test.java

/**
 * Test that the deferredTask handler is installed.
 */// w w w.j av a  2 s . c  om
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]);
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

public static byte[] doMultipartPost(String url, Map stringParams, Map fileParams) {
    PostMethod filePost = new PostMethod(url);
    Part[] parts = new Part[stringParams.size() + fileParams.size()];
    int i = 0;/*  w w w.j a v a 2s  . c om*/
    if (stringParams != null) {
        for (Iterator iter = stringParams.keySet().iterator(); iter.hasNext();) {
            String nextKey = (String) iter.next();
            String nextValue = stringParams.get(nextKey).toString();
            parts[i++] = new StringPart(nextKey, nextValue);
        }
    }
    if (fileParams != null) {
        for (Iterator iter = fileParams.keySet().iterator(); iter.hasNext();) {
            String nextKey = (String) iter.next();
            File nextValue = (File) fileParams.get(nextKey);
            try {
                parts[i++] = new FilePart(nextKey, nextValue);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    /*System.out.println("going to post multipart to url: " + url + " with parts: " + parts);
    for (int j = 0; j < parts.length; j++) {
     Part part = parts[j];
     System.out.println("current part is: " + part);
    }*/
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    //System.out.println("just set request entity");
    return executePost(filePost);
}

From source file:com.zb.app.external.wechat.service.WeixinService.java

public void upload(File file, String type) {
    StringBuilder sb = new StringBuilder(400);
    sb.append("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=");
    sb.append(getAccessToken());//ww w.  j av a  2  s  . c o m
    sb.append("&type=").append(type);

    PostMethod postMethod = new PostMethod(sb.toString());
    try {
        // FilePart?
        FilePart fp = new FilePart("filedata", file);
        Part[] parts = { fp };
        // MIMEhttpclientMulitPartRequestEntity
        MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
        postMethod.setRequestEntity(mre);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            logger.error(postMethod.getResponseBodyAsString());
        } else {
            logger.error("fail");
        }
        byte[] responseBody = postMethod.getResponseBody();
        String result = new String(responseBody, "utf-8");
        logger.error("result : " + result);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        postMethod.releaseConnection();
    }
}

From source file:com.intuit.tank.http.multipart.MultiPartRequest.java

/**
 * Execute the POST./*from  w  w w  .  j av  a  2  s .  c o  m*/
 */
public void doPost(BaseResponse response) {
    PostMethod httppost = null;
    String theUrl = null;
    try {
        URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables);
        theUrl = url.toExternalForm();
        httppost = new PostMethod(url.toString());
        String requestBody = getBody();

        List<Part> parts = buildParts();

        httppost.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), httppost.getParams()));

        sendRequest(response, httppost, requestBody);
    } catch (MalformedURLException e) {
        LOG.error(LogUtil.getLogMessage("Malformed URL Exception: " + e.toString(), LogEventType.IO), e);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(e);
    } catch (Exception ex) {
        // logger.error(LogUtil.getLogMessage(ex.toString()), ex);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(ex);
    } finally {
        if (null != httppost) {
            httppost.releaseConnection();
        }
        if (APITestHarness.getInstance().getTankConfig().getAgentConfig().getLogPostResponse()) {
            LOG.info(
                    LogUtil.getLogMessage(
                            "Response from POST to " + theUrl + " got status code " + response.getHttpCode()
                                    + " BODY { " + response.getResponseBody() + " }",
                            LogEventType.Informational));
        }
    }

}

From source file:com.apatar.flickr.function.UploadPhotoFlickrTable.java

public List<KeyInsensitiveMap> execute(FlickrNode node, Hashtable<String, Object> values, String strApi,
        String strSecret) throws IOException, XmlRpcException {
    byte[] photo = (byte[]) values.get("photo");

    int size = values.size() + 2;

    values.remove("photo");

    File newFile = ApplicationData.createFile("flicr", photo);

    PostMethod post = new PostMethod("http://api.flickr.com/services/upload");
    Part[] parts = new Part[size];

    parts[0] = new FilePart("photo", newFile);
    parts[1] = new StringPart("api_key", strApi);
    int i = 2;//w  w  w.jav a 2s  .c  o m
    for (String key : values.keySet())
        parts[i++] = new StringPart(key, values.get(key).toString());

    values.put("api_key", strApi);

    parts[i] = new StringPart("api_sig", FlickrUtils.Sign(values, strApi, strSecret));

    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status != HttpStatus.SC_OK) {
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                "Upload failed, response=" + HttpStatus.getStatusText(status));
        return null;
    } else {
        InputStream is = post.getResponseBodyAsStream();
        try {
            return createKeyInsensitiveMapFromElement(FlickrUtils.getRootElementFromInputStream(is));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:net.neurowork.cenatic.centraldir.workers.XMLPusher.java

private void pushOrganization(RestUrlManager restUrl, String token) {
    HttpClient httpclient = XMLRestWorker.getHttpClient();
    PostMethod post = new PostMethod(restUrl.getPushOrganizationUrl());

    NameValuePair tokenParam = new NameValuePair("token", token);
    NameValuePair[] params = new NameValuePair[] { tokenParam };

    post.addRequestHeader("Accept", "application/xml");
    post.setQueryString(params);/*w  w  w. ja  v  a2s.c o  m*/

    String content = XmlPushCreator.getInstance().getPushXml(organizacion);
    try {
        RequestEntity entity = new StringRequestEntity(content, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, null);
        post.setRequestEntity(entity);

        int result = httpclient.executeMethod(post);

        logger.info("Response status code: " + result);
        logger.info("Response body: ");
        logger.info(post.getResponseBodyAsString());

    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
    } catch (HttpException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } finally {
        post.releaseConnection();
    }

}

From source file:com.founder.zykc.controller.FdbzcrjryController.java

@SuppressWarnings("static-access")
@RequestMapping(value = "/queryFdbzcrjryPhoto.jpg", method = RequestMethod.GET)
public HttpEntity<byte[]> queryFdbzcrjryPhoto(String rydh, SessionBean sessionBean) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    sessionBean = getSessionBean(sessionBean);

    byte[] pictureByte = null;

    String url = "http://10.78.17.154:9999/lbs";
    String zpParameter = "operation=ForbiddenDepartureManagement_GetPhotoByID_v001&license=a756244eb0236bdc26061cb6b6bdb481&content=";
    String zpContent = "{\"data\":[{\"RYDH\":\"" + rydh + "\"}]}";
    try {//from   w  ww  .  j  a v a  2  s.  co m

        zpContent = zpParameter + java.net.URLEncoder.encode(zpContent, "UTF-8");
        PostMethod postMethod = new PostMethod(url);
        byte[] b = zpContent.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);
        HttpClient httpClient = new HttpClient();
        HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
        managerParams.setConnectionTimeout(50000);
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == 200) {
            String soapResponseData = postMethod.getResponseBodyAsString();
            JSONObject jb = JSONObject.fromObject(soapResponseData);
            if ((Integer) jb.get("datalen") > 0) {
                JSONObject jo = jb.getJSONArray("data").getJSONObject(0);

                try {
                    pictureByte = new BASE64Decoder().decodeBuffer(jo.getString("PHOTO"));
                } catch (Exception ex) {
                }
                if (pictureByte != null) {

                } else {
                    System.out.println("??" + statusCode);
                    byte[] empty_ryzp = SystemConfig.getByteArray("empty_ryzp");
                    headers.setContentLength(empty_ryzp.length);
                    return new HttpEntity(empty_ryzp, headers);
                }

            } else {
                System.out.println("??" + statusCode);
                byte[] empty_ryzp = SystemConfig.getByteArray("empty_ryzp");
                headers.setContentLength(empty_ryzp.length);
                return new HttpEntity(empty_ryzp, headers);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    headers.setContentLength(pictureByte.length);
    return new HttpEntity(pictureByte, headers);

}