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:com.intuit.tank.http.BaseRequest.java

/**
 * Execute the POST./*from   w w w  . j av a 2s.co  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();
        StringRequestEntity entity = new StringRequestEntity(requestBody, getContentType(), contentTypeCharSet);
        httppost.setRequestEntity(entity);

        sendRequest(response, httppost, requestBody);
    } catch (MalformedURLException e) {
        logger.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()) {
            logger.info(LogUtil.getLogMessage("Response from POST to " + theUrl + " got status code "
                    + response.httpCode + " BODY { " + response.response + " }", LogEventType.Informational));
        }
    }

}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

private void addWorkspace(String name) {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces";
    PostMethod post = new PostMethod(strURL);

    post.setRequestHeader("Content-type", "text/xml");
    post.setRequestEntity(
            new StringRequestEntity("<?xml version=\"1.0\"?><workspace><name>" + name + "</name></workspace>"));
    post.setDoAuthentication(true);//from   ww w  .  ja  va 2  s  .c  o  m

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(post);

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        post.releaseConnection();
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

private void publishPostGISTable(String name) {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/crwgs84/datastores/public/featuretypes";
    PostMethod post = new PostMethod(strURL);

    post.setRequestHeader("Content-type", "text/xml");
    post.setRequestEntity(new StringRequestEntity(
            "<?xml version=\"1.0\"?><featureType><name>" + name + "</name></featureType>"));
    post.setDoAuthentication(true);//from w w w.j  a v  a  2s  .  c om

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(post);

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        post.releaseConnection();
    }

}

From source file:com.intellij.lang.jsgraphql.ide.project.JSGraphQLLanguageUIProjectService.java

public void executeGraphQL(Editor editor, VirtualFile virtualFile) {
    final JSGraphQLEndpointsModel endpointsModel = editor.getUserData(JS_GRAPH_QL_ENDPOINTS_MODEL);
    if (endpointsModel != null) {
        final JSGraphQLEndpoint selectedEndpoint = endpointsModel.getSelectedItem();
        if (selectedEndpoint != null && selectedEndpoint.url != null) {
            final JSGraphQLQueryContext context = JSGraphQLQueryContextHighlightVisitor
                    .getQueryContextBufferAndHighlightUnused(editor);
            final Map<String, Object> requestData = Maps.newLinkedHashMap();
            requestData.put("query", context.query);
            try {
                requestData.put("variables", getQueryVariables(editor));
            } catch (JsonSyntaxException jse) {
                if (myToolWindowManagerInitialized) {
                    myToolWindowManager.logCurrentErrors(ContainerUtil.immutableList(
                            new JSGraphQLErrorResult("Failed to parse variables as JSON: " + jse.getMessage(),
                                    virtualFile.getPath(), "Error", 0, 0)),
                            true);/*from   www . j  ava  2  s. c o m*/
                }
                return;
            }
            final String requestJson = new Gson().toJson(requestData);
            final HttpClient httpClient = new HttpClient(new HttpClientParams());
            try {
                final PostMethod method = new PostMethod(selectedEndpoint.url);
                setHeadersFromOptions(selectedEndpoint, method);
                method.setRequestEntity(new StringRequestEntity(requestJson, "application/json", "UTF-8"));
                ApplicationManager.getApplication().executeOnPooledThread(() -> {
                    try {
                        try {
                            editor.putUserData(JS_GRAPH_QL_EDITOR_QUERYING, true);
                            StopWatch sw = new StopWatch();
                            sw.start();
                            httpClient.executeMethod(method);
                            final String responseJson = Optional.fromNullable(method.getResponseBodyAsString())
                                    .or("");
                            sw.stop();
                            final Integer errorCount = getErrorCount(responseJson);
                            if (fileEditor instanceof TextEditor) {
                                final TextEditor textEditor = (TextEditor) fileEditor;
                                UIUtil.invokeLaterIfNeeded(() -> {
                                    ApplicationManager.getApplication().runWriteAction(() -> {
                                        final Document document = textEditor.getEditor().getDocument();
                                        document.setText(responseJson);
                                        if (requestJson.startsWith("{")) {
                                            final PsiFile psiFile = PsiDocumentManager.getInstance(myProject)
                                                    .getPsiFile(document);
                                            if (psiFile != null) {
                                                new ReformatCodeProcessor(psiFile, false).run();
                                            }
                                        }
                                    });
                                    final StringBuilder queryResultText = new StringBuilder(
                                            virtualFile.getName()).append(": ").append(sw.getTime())
                                                    .append(" ms execution time, ")
                                                    .append(bytesToDisplayString(responseJson.length()))
                                                    .append(" response");

                                    if (errorCount != null && errorCount > 0) {
                                        queryResultText.append(", ").append(errorCount).append(" error")
                                                .append(errorCount > 1 ? "s" : "");
                                        if (context.onError != null) {
                                            context.onError.run();
                                        }
                                    }

                                    queryResultLabel.setText(queryResultText.toString());
                                    queryResultLabel.putClientProperty(FILE_URL_PROPERTY, virtualFile.getUrl());
                                    if (!queryResultLabel.isVisible()) {
                                        queryResultLabel.setVisible(true);
                                    }

                                    querySuccessLabel.setVisible(errorCount != null);
                                    if (querySuccessLabel.isVisible()) {
                                        if (errorCount == 0) {
                                            querySuccessLabel
                                                    .setBorder(BorderFactory.createEmptyBorder(2, 8, 0, 0));
                                            querySuccessLabel.setIcon(AllIcons.General.InspectionsOK);
                                        } else {
                                            querySuccessLabel
                                                    .setBorder(BorderFactory.createEmptyBorder(2, 12, 0, 4));
                                            querySuccessLabel.setIcon(AllIcons.Ide.ErrorPoint);
                                        }
                                    }
                                    showToolWindowContent(myProject, fileEditor.getComponent().getClass());
                                    textEditor.getEditor().getScrollingModel().scrollVertically(0);
                                });
                            }
                        } finally {
                            editor.putUserData(JS_GRAPH_QL_EDITOR_QUERYING, null);
                        }
                    } catch (IOException e) {
                        Notifications.Bus.notify(
                                new Notification("GraphQL", "GraphQL Query Error",
                                        selectedEndpoint.url + ": " + e.getMessage(), NotificationType.WARNING),
                                myProject);
                    }
                });
            } catch (UnsupportedEncodingException | IllegalStateException | IllegalArgumentException e) {
                Notifications.Bus.notify(
                        new Notification("GraphQL", "GraphQL Query Error",
                                selectedEndpoint.url + ": " + e.getMessage(), NotificationType.ERROR),
                        myProject);
            }

        }
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String testREST_POST_WorkSpace() {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces";
    PostMethod post = new PostMethod(strURL);

    post.setRequestHeader("Content-type", "text/xml");
    post.setRequestEntity(
            new StringRequestEntity("<?xml version=\"1.0\"?><workspace><name>acme2</name></workspace>"));
    post.setDoAuthentication(true);/*ww  w.  j a  v  a  2 s.c o m*/

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(post);

        System.out.println("Response: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //System.out.println(post.getResponseBodyAsStream());

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        post.releaseConnection();
    }

    return "testREST_POST_WorkSpace";
}

From source file:icom.jpa.bdk.dao.SimpleContentDAO.java

private void uploadContentBody(ManagedObjectProxy obj, DAOContext context) {
    try {/*from  w  w  w. j a  v a  2 s .  c om*/
        String resource = "session/upload";
        BdkUserContextImpl userContext = (BdkUserContextImpl) obj.getPersistenceContext().getUserContext();
        String antiCSRF = userContext.antiCSRF;
        String uploadScopeId = context.getUploadScopeId();
        String uploadContentStreamId = generateUUID();
        context.setUploadContentStreamId(uploadContentStreamId);
        String params = "uploadscope=scope" + uploadScopeId + "&content_id=" + uploadContentStreamId;
        PostMethod uploadContentMethod = preparePostMethod(resource, antiCSRF, params);
        Persistent pojoIdentifiable = obj.getPojoObject();
        ContentStreamTrait cos = (ContentStreamTrait) getAttributeValue(pojoIdentifiable,
                SimpleContentInfo.Attributes.contentBody.name());
        if (cos != null) {
            InputStream fis = cos.getFileInputStream();
            if (fis != null) {
                RequestEntity simpleText = new InputStreamRequestEntity(fis);
                uploadContentMethod.setRequestEntity(simpleText);
            }
        }
        BdkHttpUtil util = BdkHttpUtil.getInstance();
        util.upLoadContent(uploadContentMethod, userContext.httpClient);
    } catch (Exception ex) {
        throw new PersistenceException(ex);
    }
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@Test
public void testAdminUploadWithCsrfInFormField() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(
            LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);//from w ww . ja  v  a  2s. co m
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    Part csrfPart = new StringPart("csrfToken", csrfToken);
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost",
            ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part, csrfPart }, post.getParams()));
    int statusCode = HttpClientUtil.executeMethod(client, post);
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK,
            statusCode);
    String resp = post.getResponseBodyAsString();
    assertNotNull("Response should not be empty", resp);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}

From source file:com.apatar.ui.JHelpDialog.java

private void addListeners() {
    sendButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            PostMethod filePost = new PostMethod(getUrl());

            // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            try {
                List<File> targetFiles = getAttachFiles();
                Part[] parts;/* w  ww.ja va 2s.  c o m*/
                if (targetFiles != null) {
                    parts = new Part[targetFiles.size() + 1];
                    int i = 1;
                    for (File targetFile : targetFiles) {
                        parts[i++] = new FilePart("file" + i, targetFile);
                    }
                    ;
                } else
                    parts = new Part[1];

                parts[0] = new StringPart("FeatureRequest", text.getText());

                filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(filePost);
                if (status != HttpStatus.SC_OK) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                            "Upload failed, response=" + HttpStatus.getStatusText(status));
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

        }

    });
}

From source file:eu.learnpad.core.impl.cw.XwikiCoreFacadeRestResource.java

@Override
public InputStream transform(ModelSetType type, InputStream model) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/corefacade/transform", DefaultRestResource.REST_URI);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
    postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM);

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

    RequestEntity requestEntity = new InputStreamRequestEntity(model);
    postMethod.setRequestEntity(requestEntity);

    try {//from ww w  .  j a  v a2  s.  co  m
        httpClient.executeMethod(postMethod);
        return postMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.WebServiceInvoker.java

public HashMap<String, String> doPost(String relativeServiceURL) {

    PostMethod post = null;
    HttpClient httpclient = new HttpClient();
    String requestString = "";
    HashMap<String, String> responseMap = new HashMap<String, String>();

    try {//ww w  . j a v  a  2 s.  co m
        // the client id and secret is applicable across all dev orgs
        requestString = generateRequestString();
        String authorizationServerURL = CommandLineArguments.getOrgUrl() + relativeServiceURL;

        httpclient.getParams().setSoTimeout(0);
        post = new PostMethod(authorizationServerURL);
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addRequestHeader("X-PrettyPrint", "1");
        post.setRequestEntity(
                new StringRequestEntity(requestString, "application/x-www-form-urlencoded", "UTF-8"));
        httpclient.executeMethod(post);

        Gson json = new Gson();
        // obtain the result map from the response body and get the access
        // token
        responseMap = json.fromJson(post.getResponseBodyAsString(), new TypeToken<HashMap<String, String>>() {
        }.getType());

    } catch (Exception ex) {
        ApexUnitUtils.shutDownWithDebugLog(ex, "Exception during post method: " + ex);
        if (LOG.isDebugEnabled()) {
            ex.printStackTrace();
        }
    } finally {
        post.releaseConnection();
    }

    return responseMap;

}