Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#getResponseBodyAsStream()

The following examples show how to use org.apache.commons.httpclient.methods.PostMethod#getResponseBodyAsStream() . 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: ReplaceJSONPayloadTestcase.java    From micro-integrator with Apache License 2.0 8 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 2
Source File: ESBJAVA2615TestCase.java    From micro-integrator with Apache License 2.0 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 3
Source File: ReplaceJSONPayloadTestcase.java    From product-ei with Apache License 2.0 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 4
Source File: ESBJAVA2615TestCase.java    From product-ei with Apache License 2.0 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 5
Source File: AbstractSolrQueryHTTPClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException,
IOException, HttpException, URIException, JSONException
{
    PostMethod post = new PostMethod(url);
    if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER)
    {
        post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    }
    StringRequestEntity requestEntity = new StringRequestEntity(body.toString(), "application/json", "UTF-8");
    post.setRequestEntity(requestEntity);
    try
    {
        httpClient.executeMethod(post);
        if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
        {
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null)
            {
                String redirectLocation = locationHeader.getValue();
                post.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(post);
            }
        }
        if (post.getStatusCode() != HttpServletResponse.SC_OK)
        {
            throw new LuceneQueryParserException("Request failed " + post.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
        JSONObject json = new JSONObject(new JSONTokener(reader));
        return json;
    }
    finally
    {
        post.releaseConnection();
    }
}
 
Example 6
Source File: SalesforceProvisioningConnector.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private String readResponse(PostMethod post) throws IOException {
    InputStream is = post.getResponseBodyAsStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();
    return response.toString();
}
 
Example 7
Source File: ZohoServlet.java    From document-management-system with GNU General Public License v2.0 4 votes vote down vote up
/**
 *
 */
private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang) throws PathNotFoundException,
		AccessDeniedException, RepositoryException, DatabaseException, IOException, OKMException {
	Map<String, String> result = new HashMap<String, String>();
	File tmp = null;

	try {
		String path = OKMRepository.getInstance().getNodePath(null, nodeUuid);
		String fileName = PathUtils.getName(path);
		tmp = File.createTempFile("okm", ".tmp");
		InputStream is = OKMDocument.getInstance().getContent(null, path, false);
		Document doc = OKMDocument.getInstance().getProperties(null, path);
		FileOutputStream fos = new FileOutputStream(tmp);
		IOUtils.copy(is, fos);
		fos.flush();
		fos.close();

		String id = UUID.randomUUID().toString();
		String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload";
		Part[] parts = {new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY),
				new StringPart("output", "url"), new StringPart("mode", "normaledit"),
				new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY),
				new StringPart("lang", lang), new StringPart("id", id),
				new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl)};

		PostMethod filePost = new PostMethod(zohoUrl);
		filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		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) {
			log.debug("OK: " + filePost.getResponseBodyAsString());
			ZohoToken zot = new ZohoToken();
			zot.setId(id);
			zot.setUser(getThreadLocalRequest().getRemoteUser());
			zot.setNode(nodeUuid);
			zot.setCreation(Calendar.getInstance());
			ZohoTokenDAO.create(zot);

			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream()));
			String line;

			while ((line = rd.readLine()) != null) {
				if (line.startsWith("URL=")) {
					result.put("url", line.substring(4));
					result.put("id", id);
					break;
				}
			}

			rd.close();
		} else {
			String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString();
			log.error("ERROR: {}", error);
			throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error);
		}
	} finally {
		FileUtils.deleteQuietly(tmp);
	}

	return result;
}
 
Example 8
Source File: SalesforceProvisioningConnector.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * authenticate to salesforce API.
 */
private String authenticate() throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    HttpClient httpclient = new HttpClient();

    String url = configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.OAUTH2_TOKEN_ENDPOINT);

    PostMethod post = new PostMethod(StringUtils.isNotBlank(url) ?
            url : IdentityApplicationConstants.SF_OAUTH2_TOKEN_ENDPOINT);

    post.addParameter(SalesforceConnectorConstants.CLIENT_ID,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.CLIENT_ID));
    post.addParameter(SalesforceConnectorConstants.CLIENT_SECRET,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.CLIENT_SECRET));
    post.addParameter(SalesforceConnectorConstants.PASSWORD,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.PASSWORD));
    post.addParameter(SalesforceConnectorConstants.GRANT_TYPE,
            SalesforceConnectorConstants.GRANT_TYPE_PASSWORD);
    post.addParameter(SalesforceConnectorConstants.USERNAME,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.USERNAME));

    StringBuilder sb = new StringBuilder();
    try {
        // send the request
        int responseStatus = httpclient.executeMethod(post);
        if (isDebugEnabled) {
            log.debug("Authentication to salesforce returned with response code: "
                    + responseStatus);
        }

        sb.append("HTTP status " + post.getStatusCode() + " creating user\n\n");

        if (post.getStatusCode() == HttpStatus.SC_OK) {
            JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(
                    post.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Authenticate response: " + response.toString(2));
            }

            Object attributeValObj = response.opt("access_token");
            if (attributeValObj instanceof String) {
                if (isDebugEnabled) {
                    log.debug("Access token is : " + (String) attributeValObj);
                }
                return (String) attributeValObj;
            } else {
                log.error("Authentication response type : " + attributeValObj.toString()
                        + " is invalide");
            }
        } else {
            log.error("recieved response status code :" + post.getStatusCode() + " text : "
                    + post.getStatusText());
        }
    } catch (JSONException | IOException e) {
        throw new IdentityProvisioningException("Error in decoding response to JSON", e);
    } finally {
        post.releaseConnection();
    }

    return "";
}
 
Example 9
Source File: CitationParser.java    From bluima with Apache License 2.0 4 votes vote down vote up
public Citation parse(String citationStr) throws HttpException,
        IOException, ParserConfigurationException, SAXException {

    PostMethod method = new PostMethod(url);
    method.addRequestHeader("accept", "text/xml");
    method.addParameter("citation", citationStr);

    int statusCode = client.executeMethod(method);

    if (statusCode != -1) {
        InputStream in = method.getResponseBodyAsStream();

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(in);
        doc.getDocumentElement().normalize();

        NodeList nodes = doc.getElementsByTagName("citation");

        // for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(0);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;

            String isValid = element.getAttribute("valid");
            if (isValid.equals("true")) {
                Citation citation = new Citation();

                citation.setTitle(getValue("title", element));
                citation.setYear(new Integer(getValue("year", element)));

                NodeList authors = element.getElementsByTagName("author");
                for (int j = 0; j < authors.getLength(); j++) {
                    Node author = authors.item(j);
                    citation.addAuthor(author.getTextContent());
                }
                return citation;
            }
        }
    }
    return null;
}