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

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

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.kubeiwu.commontool.khttp.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///ww w  .  java 2s.  co  m
/* protected */static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.sonar.plugins.buildstability.ci.jenkins.JenkinsUtils.java

public static void doLogin(HttpClient client, String hostName, String username, String password)
        throws IOException {
    String hudsonLoginEntryUrl = hostName + "/login";
    HttpGet loginLink = new HttpGet(hudsonLoginEntryUrl);
    HttpResponse response = client.execute(loginLink);
    checkResult(response.getStatusLine().getStatusCode(), hudsonLoginEntryUrl);
    EntityUtils.consume(response.getEntity());

    String location = hostName + "/j_acegi_security_check";
    boolean loggedIn = false;
    while (!loggedIn) {
        HttpPost loginMethod = new HttpPost(location);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", username));
        nvps.add(new BasicNameValuePair("j_password", password));
        nvps.add(new BasicNameValuePair("action", "login"));
        loginMethod.setEntity(new UrlEncodedFormEntity(nvps));
        try {/* www .j  a v  a2  s  .c  om*/
            HttpResponse response2 = client.execute(loginMethod);
            if (response2.getStatusLine().getStatusCode() / 100 == 3) {
                // Commons HTTP client refuses to handle redirects for POST
                // so we have to do it manually.
                location = response2.getFirstHeader("Location").getValue();
            } else {
                checkResult(response2.getStatusLine().getStatusCode(), location);
                loggedIn = true;
            }
            EntityUtils.consume(response2.getEntity());
        } finally {
            loginMethod.releaseConnection();
        }
    }
}

From source file:com.afrisoftech.lib.PDF2ExcelConverter.java

public static void convertPDf2Excel(String pdfFile2Convert) throws Exception {
    if (pdfFile2Convert.length() < 3) {
        System.out.println("File to convert is mandatory!");
        javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
    } else {//from   ww  w  .ja  v a2s. c om

        final String apiKey = "ktxpfvf0i5se";
        final String format = "xlsx-single".toLowerCase();
        final String pdfFilename = pdfFile2Convert;

        if (!formats.contains(format)) {
            System.out.println("Invalid output format: \"" + format + "\"");
        }

        // Avoid cookie warning with default cookie configuration
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

        File inputFile = new File(pdfFilename);

        if (!inputFile.canRead()) {
            System.out.println("Can't read input PDF file: \"" + pdfFilename + "\"");
            javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
        }

        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .build()) {
            HttpPost httppost = new HttpPost("https://pdftables.com/api?format=" + format + "&key=" + apiKey);
            FileBody fileBody = new FileBody(inputFile);

            HttpEntity requestBody = MultipartEntityBuilder.create().addPart("f", fileBody).build();
            httppost.setEntity(requestBody);

            System.out.println("Sending request");

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    System.out.println(response.getStatusLine());
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Internet connection is a must. Consult IT administrator for further assistance");
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    final String outputFilename = getOutputFilename(pdfFilename,
                            format.replaceFirst("-.*$", ""));
                    System.out.println("Writing output to " + outputFilename);

                    final File outputFile = new File(outputFilename);
                    FileUtils.copyInputStreamToFile(resEntity.getContent(), outputFile);
                    if (java.awt.Desktop.isDesktopSupported()) {
                        try {
                            java.awt.Desktop.getDesktop().open(outputFile);
                        } catch (IOException ex) {
                            javax.swing.JOptionPane.showMessageDialog(new java.awt.Frame(), ex.getMessage());
                            ex.printStackTrace(); //Exceptions.printStackTrace(ex);
                        }
                    }
                } else {
                    System.out.println("Error: file missing from response");
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Error: file missing from response! Internet connection is a must.");
                }
            }
        }
    }
}

From source file:YexTool.java

private static OpenRtb.BidResponse sendBidRequest(String dspServerAddress, OpenRtb.BidRequest bidRequest,
        String dataFormat) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(dspServerAddress);
    switch (dataFormat) {
    case "pb":
        post.setEntity(new ByteArrayEntity(bidRequest.toByteArray()));
        post.setHeader("Content-Type", "application/x-protobuf");
        break;//w  ww.  jav a 2s . co m
    case "js":
        post.setEntity(new StringEntity(openRtbJsonFactory.newWriter().writeBidRequest(bidRequest)));
        post.setHeader("Content-Type", "application/json");
        break;
    case "jo":
        post.setEntity(new StringEntity(yexOpenRtbJsonFactory.newWriter().writeBidRequest(bidRequest)));
        post.setHeader("Content-Type", "application/json");
        break;
    }

    logger.info("Sending BidRequest to URL: " + dspServerAddress);
    HttpResponse response = httpclient.execute(post);

    OpenRtb.BidResponse bidResponse = null;
    if (response.getStatusLine().getStatusCode() == 200) {
        try {
            switch (dataFormat) {
            case "pb":
                bidResponse = OpenRtb.BidResponse.parseFrom(response.getEntity().getContent(),
                        extensionRegistry);
                break;
            case "js":
                bidResponse = openRtbJsonFactory.newReader().readBidResponse(response.getEntity().getContent());
                OpenRtb.BidResponse.Builder bidResponseBuilder = bidResponse.toBuilder().clearSeatbid();
                for (OpenRtb.BidResponse.SeatBid seatBid : bidResponse.getSeatbidList()) {
                    OpenRtb.BidResponse.SeatBid.Builder seatBidBuilder = seatBid.toBuilder().clearBid();
                    for (OpenRtb.BidResponse.SeatBid.Bid bid : seatBid.getBidList()) {
                        seatBidBuilder.addBid(bid.toBuilder().clearAdm().setAdmNative(
                                openRtbJsonFactory.newNativeReader().readNativeResponse(bid.getAdm())));
                    }
                    bidResponseBuilder.addSeatbid(seatBidBuilder);
                }
                bidResponse = bidResponseBuilder.build();
                break;
            case "jo":
                bidResponse = yexOpenRtbJsonFactory.newReader()
                        .readBidResponse(response.getEntity().getContent());
                break;
            }
        } catch (Exception e) {
            throw new Exception("Error while parse HttpResponse to BidResponse!", e);
        }
        bidResponse = electValidBidsInBidResponse(bidRequest, bidResponse);
    } else {
        logger.error("Error Response Code: " + response.getStatusLine().getStatusCode());
    }

    return bidResponse;
}

From source file:com.rumblefish.friendlymusic.api.WebRequest.java

public static String webRequest(URLRequest request) {
    HttpPost httpPost = null;
    HttpGet httpGet = null;/*from   ww  w.j  a  va  2 s . c  o m*/
    if (request.m_nameValuePairs != null) {
        httpPost = new HttpPost(request.m_serverURL);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(request.m_nameValuePairs));
        } catch (Exception e) {
            return null;
        }
    } else {
        httpGet = new HttpGet(request.m_serverURL);
        Log.v(LOGTAG, request.m_serverURL);
    }

    HttpClient client = getNewHttpClient(request.m_timelimit);

    StringBuilder builder = new StringBuilder();

    try {
        HttpResponse response;
        if (request.m_nameValuePairs != null)
            response = client.execute(httpPost);
        else
            response = client.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            try {
                content.close();
            } catch (IOException e) {

            }
        } else {
            Log.e("WebRequest", "Failed to download file");
            return null;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().closeExpiredConnections();
        client.getConnectionManager().closeIdleConnections(0, TimeUnit.NANOSECONDS);
    }

    String resultString = builder.toString();
    try {
        if (resultString == null || resultString.length() == 0) {
            return null;
        }
        return resultString;
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static byte[] doPostSubmit(String url, Map<String, Object> params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost();
    try {/*  w w  w  .j  a v a 2s.  c o m*/

        List<NameValuePair> list = new ArrayList<NameValuePair>();

        for (Entry<String, Object> entry : params.entrySet()) {
            NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
            list.add(nameValuePair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toByteArray(entity);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:co.cask.cdap.gateway.handlers.metrics.MetricsSuiteTestBase.java

public static HttpResponse doPost(String resource, String body, Header[] headers) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(MetricsSuiteTestBase.getEndPoint(resource));
    if (body != null) {
        post.setEntity(new StringEntity(body));
    }/*from   w ww  .  j  a v  a 2s  .  com*/

    if (headers != null) {
        post.setHeaders(ObjectArrays.concat(AUTH_HEADER, headers));
    } else {
        post.setHeader(AUTH_HEADER);
    }
    return client.execute(post);
}

From source file:email.mandrill.SendMail.java

public static void checkPingPong() {
    try {//from   w ww .  j av a2 s . com
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("https://mandrillapp.com/api/1.0/users/ping.json");

        JSONObject obj = new JSONObject();
        obj.put("key", SendEmail.MANDRILL_KEY);
        String request = obj.toString();
        HttpEntity entity = new ByteArrayEntity(request.getBytes("UTF-8"));
        httppost.setEntity(entity);
        //Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            InputStream instream = responseEntity.getContent();
            try {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                String theString = writer.toString();
                logger.log(Level.INFO, theString);
            } finally {
                instream.close();
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, util.Utility.logMessage(e, "Exception while updating org name:", null));
    }
}

From source file:Main.java

public static String getResultPost(String uri, List<NameValuePair> params) {
    String Result = null;/*from w  ww  .j  ava  2 s  . co  m*/
    try {
        if (uri == null) {
            return "";
        }
        HttpPost httpRequest = new HttpPost(uri);
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpResponse httpResponse = httpClient.execute(httpRequest);
        int res = httpResponse.getStatusLine().getStatusCode();
        if (res == 200) {

            StringBuilder builder = new StringBuilder();
            BufferedReader bufferedReader2 = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));
            for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2.readLine()) {
                builder.append(s);
            }
            Result = builder.toString();

        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block

        e.printStackTrace();
        return "";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Result;
}

From source file:org.lol.reddit.account.RedditAccount.java

public static LoginResultPair login(final Context context, final String username, final String password,
        final HttpClient client) {

    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3);
    fields.add(new BasicNameValuePair("user", username));
    fields.add(new BasicNameValuePair("passwd", password));
    fields.add(new BasicNameValuePair("api_type", "json"));

    // TODO put somewhere else
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 5);

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login");
    request.setParams(params);/*from  w  ww .  ja v a 2 s  .c o  m*/

    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        return new LoginResultPair(LoginResult.INTERNAL_ERROR);
    }

    final PersistentCookieStore cookies = new PersistentCookieStore();

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    final StatusLine status;
    final HttpEntity entity;
    try {
        final HttpResponse response = client.execute(request, localContext);
        status = response.getStatusLine();
        entity = response.getEntity();

    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    if (status.getStatusCode() != 200) {
        return new LoginResultPair(LoginResult.REQUEST_ERROR);
    }

    final JsonValue result;

    try {
        result = new JsonValue(entity.getContent());
        result.buildInThisThread();
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    final String modhash;

    try {

        // TODO use the more general reddit error finder
        final JsonBufferedArray errors = result.asObject().getObject("json").getArray("errors");
        errors.join();
        if (errors.getCurrentItemCount() != 0) {

            for (final JsonValue v : errors) {
                for (final JsonValue s : v.asArray()) {

                    // TODO handle unknown messages by concatenating all Reddit's strings

                    if (s.getType() == JsonValue.Type.STRING) {

                        Log.i("RR DEBUG ERROR", s.asString());

                        // lol, reddit api
                        if (s.asString().equalsIgnoreCase("WRONG_PASSWORD")
                                || s.asString().equalsIgnoreCase("invalid password")
                                || s.asString().equalsIgnoreCase("passwd"))
                            return new LoginResultPair(LoginResult.WRONG_PASSWORD);

                        if (s.asString().contains("too much")) // also "RATELIMIT", but that's not as descriptive
                            return new LoginResultPair(LoginResult.RATELIMIT, s.asString());
                    }
                }
            }

            return new LoginResultPair(LoginResult.UNKNOWN_REDDIT_ERROR);
        }

        final JsonBufferedObject data = result.asObject().getObject("json").getObject("data");

        modhash = data.getString("modhash");

    } catch (NullPointerException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (InterruptedException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    }

    return new LoginResultPair(LoginResult.SUCCESS, new RedditAccount(username, modhash, cookies, 0), null);
}