Example usage for org.apache.http.client.methods HttpPost HttpPost

List of usage examples for org.apache.http.client.methods HttpPost HttpPost

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost HttpPost.

Prototype

public HttpPost(final String uri) 

Source Link

Usage

From source file:sce.HTTPPostReq.java

HttpPost createConnectivity(String restUrl, String username, String password, int timeout) {
    HttpPost post = new HttpPost(restUrl);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).build();
    post.setConfig(requestConfig);//w  ww.j a va2s. c  o  m
    if (username != null && password != null) {
        String auth = new StringBuffer(username).append(":").append(password).toString();
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        post.setHeader("AUTHORIZATION", authHeader);
    }
    post.setHeader("Content-Type", "application/json");
    post.setHeader("Accept", "application/json");
    post.setHeader("Accept-Enconding", "UTF-8");
    post.setHeader("X-Stream", "true");
    return post;
}

From source file:com.splunk.shuttl.server.mbeans.util.EndpointUtils.java

public static HttpPost createHttpPost(URI endpoint, Object... kvs) {
    HttpPost httpPost = new HttpPost(endpoint);
    setParamsToPostRequest(httpPost, createHttpParams(kvs));
    return httpPost;
}

From source file:org.fastcatsearch.util.HTMLTagRemoverTest.java

public void test1() {
    HttpClient httpclient = new DefaultHttpClient();
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    HttpPost httpost = new HttpPost("http://www.fastcatsearch.org/");
    HttpGet httpGet = new HttpGet("http://www.fastcatsearch.org/");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    try {/*from  w w  w. j av a2 s  . c o  m*/
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        String responseBody = httpclient.execute(httpGet, responseHandler);

        System.out.println(HTMLTagRemover.clean(responseBody));

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.utils.HttpQueryUtils.java

public static String[] fileUpload(String uploadUrl, String name, byte[] byteArray) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uploadUrl);
    String paramName = "vehicle";
    String paramValue = name;/* w w w .  ja  v a 2 s .c o m*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart(paramName, new InputStreamBody((new ByteArrayInputStream(byteArray)), "application/zip"));
    entity.addPart(paramName, new StringBody(paramValue, "text/plain", Charset.forName("UTF-8")));
    httppost.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(httppost);
    StatusLine statusLine = httpResponse.getStatusLine();
    String reason = statusLine.getReasonPhrase();
    int rc = statusLine.getStatusCode();
    String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
    httpclient.getConnectionManager().shutdown();
    return new String[] { String.valueOf(rc), reason, response };
}

From source file:org.fcrepo.integration.api.FedoraIdentifiersIT.java

@Test
public void testGetNextHasAPid() throws IOException {
    final HttpPost method = new HttpPost(serverAddress + "nextPID?numPids=1");
    method.addHeader("Accepts", "text/xml");
    final HttpResponse response = client.execute(method);
    logger.debug("Executed testGetNextHasAPid()");
    final String content = EntityUtils.toString(response.getEntity());
    logger.debug("Only to find:\n" + content);
    assertTrue("Didn't find a single dang PID!", compile("<pid>.*?</pid>", DOTALL).matcher(content).find());
}

From source file:com.testmax.uri.HttpRestWebservice.java

public String handleHTTPPostUnit() throws Exception {
    String resp = null;/*from  w  w  w  .j  av a2 s  .c  o  m*/

    String replacedParam = "";
    System.out.println(this.url);
    HttpPost httpost = new HttpPost(this.url);
    //System.out.println(this.url);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    URLConfig urlConf = this.page.getURLConfig();

    Set<String> s = urlConf.getUrlParamset();
    for (String param : s) {
        replacedParam = urlConf.getUrlParamValue(param);
        System.out.println(urlConf.getUrlParamValue(param));
        nvps.add(new BasicNameValuePair(param, urlConf.getUrlParamValue(param)));
    }

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    //set the time for this HTTP resuest
    this.startRecording();
    long starttime = this.getCurrentTime();
    HttpResponse response = this.httpsclient.execute(httpost);
    HttpEntity entity = response.getEntity();
    // Measure the time passed between response
    long elaspedTime = this.getElaspedTime(starttime);
    this.stopRecording(response, elaspedTime);
    resp = this.getResponseBodyAsString(entity);
    System.out.println(resp);
    System.out.println("ElaspedTime: " + elaspedTime);
    WmLog.getCoreLogger().info("Response XML: " + resp);
    WmLog.getCoreLogger().info("ElaspedTime: " + elaspedTime);
    this.printRecording();
    this.printLog();
    if (this.getResponseStatus() == 200 && validateAssert(urlConf, resp)) {
        this.addThreadActionMonitor(this.action, true, elaspedTime);
    } else {
        this.addThreadActionMonitor(this.action, false, elaspedTime);
        WmLog.getCoreLogger().info("Input XML: " + replacedParam);
        WmLog.getCoreLogger().info("Response XML: " + resp);
    }
    this.closeEntity(entity);
    return (resp);

}

From source file:movie.rating.retriever.JSONResponse.java

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) throws Exception {

    // Making HTTP request

    // check for request method
    if (method == "POST") {
        // request method is POST
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();//from ww w .  j a v  a  2 s  .c om

    } else if (method == "GET") {
        // request method is GET
        DefaultHttpClient httpClient = new DefaultHttpClient();
        if (params != null) {
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
        }
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 20);
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        System.out.println("Error converting result " + e.toString());
    }

    // try parse the string to a JSON object

    //System.out.println("JSON String"+ json);
    try {
        jObj = new JSONObject(json);

    } catch (Exception e) {
        System.out.println("Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

From source file:org.dataconservancy.ui.it.support.ListProjectCollectionsRequest.java

public HttpPost asHttpPost(String projectId) {

    HttpPost post = null;/*from  w w  w .  ja va2s . co  m*/
    try {
        post = new HttpPost(urlConfig.getListProjectCollectionsUrl().toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("currentProjectId", projectId));
    params.add(new BasicNameValuePair(STRIPES_EVENT, "List Project Collections"));

    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    post.setEntity(entity);

    return post;
}

From source file:org.wso2.carbon.governance.registry.extensions.utils.APIUtils.java

/**
 * This method will authenticate the user name and password mentioned in life cycle against APIM.
 *
 * @param httpContext/*from   www .j a  v a  2 s .c om*/
 * @param apimEndpoint
 * @param apimUsername
 * @param apimPassword
 */
public static void authenticateAPIM(HttpContext httpContext, String apimEndpoint, String apimUsername,
        String apimPassword) throws GovernanceException {

    String loginEP = apimEndpoint + Constants.APIM_LOGIN_ENDPOINT;
    try {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(loginEP);
        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>(Constants.APIM_PARAMETER_COUNT);

        params.add(new BasicNameValuePair(API_ACTION, API_LOGIN_ACTION));
        params.add(new BasicNameValuePair(API_USERNAME, apimUsername));
        params.add(new BasicNameValuePair(API_PASSWORD, apimPassword));
        httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));

        HttpResponse response = httpclient.execute(httppost, httpContext);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, Constants.UTF_8_ENCODE);
        if (response.getStatusLine().getStatusCode() != Constants.SUCCESS_RESPONSE_CODE) {
            throw new RegistryException(" Authentication with APIM failed: HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        Gson gson = new Gson();
        ResponseAPIM responseAPIM = gson.fromJson(responseString, ResponseAPIM.class);
        if (responseAPIM.getError().equalsIgnoreCase("true")) {
            throw new GovernanceException(
                    "Error occurred in validating the user. Please check the credentials");
        }

    } catch (Exception e) {
        throw new GovernanceException("Authentication failed with API Manager. Please check the credentials",
                e);
    }
}

From source file:org.opencastproject.remotetest.server.resource.ComposerResources.java

public static HttpResponse image(TrustedHttpClient client, String mediapackage, String time,
        String sourceTrackId, String profileId) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "encode");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("mediapackage", mediapackage));
    params.add(new BasicNameValuePair("sourceTrackId", sourceTrackId));
    params.add(new BasicNameValuePair("time", time));
    params.add(new BasicNameValuePair("profileId", profileId));
    post.setEntity(new UrlEncodedFormEntity(params));
    return client.execute(post);
}