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

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.fhc25.percepcion.osiris.mapviewer.common.restutils.RestClient.java

/**
 * Executes the requests.//w ww  . j av  a  2 s. c o  m
 *
 * @param method   the type of method (POST, GET, DELETE, PUT).
 * @param url      the url of the request.
 * @param headers  the headers to include.
 * @param listener a listener for callbacks.
 * @throws Exception
 */
public static void Execute(final File file, final RequestMethod method, final String url,
        final ArrayList<NameValuePair> headers, final RestListener listener) throws Exception {
    new Thread() {
        @Override
        public void run() {

            switch (method) {
            case GET:
                // Do nothing
                break;

            case POST: {

                HttpPost request = new HttpPost(url);
                // add headers
                if (headers != null) {
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }

                // code file
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                Log.d(TAG, "UPLOAD: file length = " + file.length());
                Log.d(TAG, "UPLOAD: file exist = " + file.exists());
                FileBody bodyPart = new FileBody(file);
                entity.addPart("file", bodyPart);
                request.setEntity(entity);

                Log.i(TAG, "Request with File:" + request.getEntity());

                executeRequest(request, url, listener);
            }
                break;

            case PUT: {
                HttpPut request = new HttpPut(url);
                // add headers
                if (headers != null) {
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }

                // code file
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                Log.d(TAG, "UPLOAD: file length = " + file.length());
                Log.d(TAG, "UPLOAD: file exist = " + file.exists());
                FileBody bodyPart = new FileBody(file);
                entity.addPart("file", bodyPart);
                request.setEntity(entity);

                Log.v(TAG, "Request " + request.toString());
                executeRequest(request, url, listener);
            }
                break;

            case DELETE:
                // Do nothing
                break;

            } // switch end
        }
    }.start();
}

From source file:dataServer.StorageRESTClientManager.java

public boolean updateKPIStorage(String kpiInfo) {

    // Default HTTP response and common properties for responses
    HttpResponse response = null;//from   w w w  . j a  v  a  2s  .co  m
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    try {
        HttpPost query = new HttpPost(StreamPipes);
        query.setHeader("Content-type", "application/json");
        query.setEntity(new StringEntity(kpiInfo));

        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");
        System.out.println(kpiInfo);
        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");
        System.out.println(query.toString());
        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");

        response = client.execute(query);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            //throw new RuntimeException("Failed! HTTP error code: " + status);
            System.out.println("Error accessing storage: " + status);

            return false;
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        //result
        return true;

    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return false;
    }
}

From source file:dataServer.StorageRESTClientManager.java

public boolean insertKPIStorage(String kpiInfo) {

    // Default HTTP response and common properties for responses
    HttpResponse response = null;//from  www .j  a v a 2s. c  o m
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    try {
        HttpPost query = new HttpPost(StreamPipes);
        query.setHeader("Content-type", "application/json");
        query.setEntity(new StringEntity(kpiInfo));

        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");
        System.out.println(kpiInfo);
        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");
        System.out.println(query.toString());
        System.out.println(
                "\n\n\n########################################################################################################\n\n\n");

        response = client.execute(query);

        System.out.println("\n\n\nResponse:\n" + response.toString());

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {

            //throw new RuntimeException("Failed! HTTP error code: " + status);
            //apagar kpi da BD
            System.out.println("Error accessing storage: " + status);

            return false;
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        //result
        return true;

    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return false;
    }
}

From source file:eu.seaclouds.platform.planner.core.utils.HttpHelper.java

/**
 * @param restPath//from  w  w  w.j a va  2s .  c  o m
 * @param params
 * @return
 */
public Pair<String, String> postRequest(String restPath, List<NameValuePair> params) {
    log.info("Posting request for " + this.serviceURL + restPath);
    HttpPost httpPost = new HttpPost(prepareRequestURL(restPath, new ArrayList<NameValuePair>()));
    CloseableHttpResponse response = null;
    String content = "";
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {
            content = EntityUtils.toString(entity);
        } else {
            content = response.getStatusLine().getReasonPhrase();
        }

        EntityUtils.consume(entity);
        log.info("Post success");
        return new Pair<String, String>(String.valueOf(status), content);

    } catch (UnsupportedEncodingException e) {
        log.error("UnsupportedEncodingException", e);
    } catch (ClientProtocolException e) {
        log.error("ClientProtocolException", e);
    } catch (IOException e) {
        log.error("IOException", e);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            log.error("IOException", e);
        }
    }
    return new Pair<>("500", "Post Exception for: " + httpPost.toString());
}

From source file:com.osamashabrez.clientserver.json.ClientServerJSONActivity.java

/** Called when the activity is first created. */
@Override//  w w w  .  j av  a 2s  .  co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    buildref = (EditText) findViewById(R.id.editTextbuild);
    buildref.setFocusable(false);
    buildref.setClickable(false);
    recvdref = (EditText) findViewById(R.id.editTextrecvd);
    recvdref.setFocusable(false);
    recvdref.setClickable(false);
    JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
    jsonobj = new JSONObject();
    try {
        // adding some keys
        jsonobj.put("key", "value");
        jsonobj.put("weburl", "hashincludetechnology.com");

        // lets add some headers (nested headers)
        JSONObject header = new JSONObject();
        header.put("devicemodel", android.os.Build.MODEL); // Device model
        header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
        header.put("language", Locale.getDefault().getISO3Language()); // Language
        jsonobj.put("header", header);
        // Display the contents of the JSON objects
        buildref.setText(jsonobj.toString(2));
    } catch (JSONException ex) {
        buildref.setText("Error Occurred while building JSON");
        ex.printStackTrace();
    }
    // Now lets begin with the server part
    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppostreq = new HttpPost(wurl);
        StringEntity se = new StringEntity(jsonobj.toString());
        //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        se.setContentType("application/json;charset=UTF-8");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        httppostreq.setEntity(se);
        //           httppostreq.setHeader("Accept", "application/json");
        //           httppostreq.setHeader("Content-type", "application/json");
        //           httppostreq.setHeader("User-Agent", "android");
        HttpResponse httpresponse = httpclient.execute(httppostreq);
        HttpEntity resultentity = httpresponse.getEntity();
        if (resultentity != null) {
            InputStream inputstream = resultentity.getContent();
            Header contentencoding = httpresponse.getFirstHeader("Content-Encoding");
            if (contentencoding != null && contentencoding.getValue().equalsIgnoreCase("gzip")) {
                inputstream = new GZIPInputStream(inputstream);
            }

            String resultstring = convertStreamToString(inputstream);
            inputstream.close();
            resultstring = resultstring.substring(1, resultstring.length() - 1);
            recvdref.setText(resultstring + "\n\n" + httppostreq.toString().getBytes());
            //              JSONObject recvdjson = new JSONObject(resultstring);
            //               recvdref.setText(recvdjson.toString(2));
        }
    } catch (Exception e) {
        recvdref.setText("Error Occurred while processing JSON");
        recvdref.setText(e.getMessage());
    }
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

private void getAccessToken() throws IOException, SDKException {

    HttpPost httpPost = new HttpPost(provider);

    httpPost.setHeader("Authorization", "Basic " + encoding);
    List<BasicNameValuePair> parametersBody = new ArrayList<>();
    parametersBody.add(new BasicNameValuePair("grant_type", "password"));
    parametersBody.add(new BasicNameValuePair("username", this.username));
    parametersBody.add(new BasicNameValuePair("password", this.password));

    log.debug("Username is: " + username);
    log.debug("Password is: " + password);

    httpPost.setEntity(new UrlEncodedFormEntity(parametersBody, StandardCharsets.UTF_8));

    CloseableHttpResponse response = null;
    log.debug("httpPost is: " + httpPost.toString());
    response = httpClient.execute(httpPost);
    String responseString = null;
    responseString = EntityUtils.toString(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    response.close();/*from  www  .  j av a 2s  . c o m*/
    httpPost.releaseConnection();
    log.trace(statusCode + ": " + responseString);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    if (statusCode != 200) {
        JsonObject error = gson.fromJson(responseString, JsonObject.class);

        JsonElement detailMessage = error.get("detailMessage");
        if (detailMessage == null)
            detailMessage = error.get("errorMessage");
        if (detailMessage == null)
            detailMessage = error.get("message");
        if (detailMessage == null)
            detailMessage = error.get("description");
        if (detailMessage == null)
            detailMessage = error.get("errorDescription");

        log.error("Status Code [" + statusCode + "]: Error signing-in ["
                + (detailMessage != null ? detailMessage.getAsString() : "no error description") + "]");

        if (detailMessage == null)
            log.error("Got Error from server: \n" + gson.toJson(error));
        throw new SDKException("Status Code [" + statusCode + "]: Error signing-in ["
                + (detailMessage != null ? detailMessage.getAsString() : "no error description") + "]");
    }
    JsonObject jobj = new Gson().fromJson(responseString, JsonObject.class);
    log.trace("JsonTokeAccess is: " + jobj.toString());
    try {
        String token = jobj.get("value").getAsString();
        log.trace(token);
        bearerToken = "Bearer " + token;
        this.token = token;
    } catch (NullPointerException e) {
        String error = jobj.get("error").getAsString();
        if (error.equals("invalid_grant")) {
            throw new SDKException(
                    "Error during authentication: " + jobj.get("error_description").getAsString(), e);
        }
    }
}

From source file:com.epic.framework.implementation.tapjoy.TapjoyURLConnection.java

/**
 * Performs a network request call using HTTP POST to the specified URL and parameters.
 * /*  ww w.  j ava 2 s. co m*/
 * @param url                     The URL to connect to.
 * @param params                  POST parameters in key/value format.
 * @param paramsData               Any additional POST parameters in key/value format.
 * @return                         Response from the server.
 */
public String connectToURLwithPOST(String url, Hashtable<String, String> params,
        Hashtable<String, String> paramsData) {
    String httpResponse = null;

    try {
        String requestURL = url;

        // Replaces all spaces.
        requestURL = requestURL.replaceAll(" ", "%20");

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "baseURL: " + url);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL);

        HttpPost httpPost = new HttpPost(requestURL);

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

        Set<Entry<String, String>> entries = params.entrySet();
        Iterator<Entry<String, String>> iterator = entries.iterator();

        while (iterator.hasNext()) {
            Entry<String, String> item = iterator.next();
            pairs.add(new BasicNameValuePair(item.getKey(), item.getValue()));

            TapjoyLog.i(TAPJOY_URL_CONNECTION,
                    "key: " + item.getKey() + ", value: " + Uri.encode(item.getValue()));
        }

        if (paramsData != null && paramsData.size() > 0) {
            entries = paramsData.entrySet();
            iterator = entries.iterator();

            while (iterator.hasNext()) {
                Entry<String, String> item = iterator.next();
                pairs.add(new BasicNameValuePair("data[" + item.getKey() + "]", item.getValue()));

                TapjoyLog.i(TAPJOY_URL_CONNECTION,
                        "key: " + item.getKey() + ", value: " + Uri.encode(item.getValue()));
            }
        }

        httpPost.setEntity(new UrlEncodedFormEntity(pairs));

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "HTTP POST: " + httpPost.toString());

        // Create a HttpParams object so we can set our timeout times.
        HttpParams httpParameters = new BasicHttpParams();

        // Time to wait to establish initial connection.
        HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);

        // Time to wait for incoming data.
        HttpConnectionParams.setSoTimeout(httpParameters, 30000);

        // Create a http client with out timeout settings.
        HttpClient client = new DefaultHttpClient(httpParameters);

        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();

        httpResponse = EntityUtils.toString(entity);

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response status: " + response.getStatusLine().getStatusCode());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response size: " + httpResponse.length());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response: ");
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "" + httpResponse);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString());
    }

    return httpResponse;
}

From source file:org.easit.core.controllers.signin.SigninController.java

/**
 * Internal helpers//from  w  ww  . j  ava2  s.  c om
 * Exchange the authorization code for an access token
 */
private String exchange_code_for_access_token(WebRequest request) throws Exception {
    // Exchange the authorization code for an access token
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(environment.getProperty("flowManager.url")
            + environment.getProperty("flowManager.exchange_accesstoken"));

    // add header 
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
    urlParameters.add(new BasicNameValuePair("code", request.getParameter("code")));
    urlParameters.add(new BasicNameValuePair("redirect_uri",
            environment.getProperty("project.url") + "/oauth_signin/authorize_callback"));
    urlParameters.add(new BasicNameValuePair("client_id", environment.getProperty("flowManager.client_id")));
    urlParameters
            .add(new BasicNameValuePair("client_secret", environment.getProperty("flowManager.client_secret")));
    post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));

    //Exchange the authorization code for an access token
    HttpResponse response = client.execute(post);

    //NOT Correct answer
    if (response.getStatusLine().getStatusCode() != 200) {

        logger.info("ERROR:");
        logger.info("URL target: " + environment.getProperty("flowManager.url")
                + environment.getProperty("flowManager.exchange_accesstoken"));

        logger.info(post.toString());
        for (Header header : post.getAllHeaders()) {
            logger.info(header.getName() + " : " + header.getValue());
        }

        String content = EntityUtils.toString(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
        logger.info("");
        logger.info(content);
        logger.info("");

        logger.info("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    logger.info("ACCESS:" + result);

    //Extract the access token
    JSONObject json = new JSONObject(result.toString());
    Map<String, String> output = new HashMap<String, String>();
    CoreUtils.parse(json, output);
    return output.get("access_token");
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse createStack(String template, String stackName) throws IOException {

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpPost createStack = null;
    HttpResponse response = null;/*  ww  w.  jav a2 s.co  m*/

    String jsonTemplate = JavaStackUtils.convertYamlToJson(template);
    JSONObject modifiedObject = new JSONObject();
    modifiedObject.put("stack_name", stackName);
    modifiedObject.put("template", new JSONObject(jsonTemplate));

    if (this.isAuthenticated) {
        StringBuilder buildUrl = new StringBuilder();
        buildUrl.append("http://");
        buildUrl.append(this.endpoint);
        buildUrl.append(":");
        buildUrl.append(Constants.HEAT_PORT.toString());
        buildUrl.append(String.format("/%s/%s/stacks", Constants.HEAT_VERSION.toString(), tenant_id));

        // Logger.debug(buildUrl.toString());
        createStack = new HttpPost(buildUrl.toString());
        createStack.setEntity(new StringEntity(modifiedObject.toString(), ContentType.APPLICATION_JSON));
        // Logger.debug(this.token_id);
        createStack.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        Logger.debug("Request: " + createStack.toString());
        Logger.debug("Request body: " + modifiedObject.toString());

        response = httpClient.execute(createStack);
        int statusCode = response.getStatusLine().getStatusCode();
        String responsePhrase = response.getStatusLine().getReasonPhrase();

        Logger.debug("Response: " + response.toString());
        Logger.debug("Response body:");

        if (statusCode != 201) {
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = null;

            while ((line = in.readLine()) != null)
                Logger.debug(line);
        }

        return (statusCode == 201) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode,
                        responsePhrase + ". Create Failed with Status: " + statusCode), null);
    } else {
        throw new IOException("You must Authenticate before issuing this request, please re-authenticate. ");
    }
}

From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java

public void execute() throws MojoExecutionException {
    this.getLog().info("Uploading project to BukkitDev");
    final String gameVersion = this.getGameVersion();
    final URIBuilder builder = new URIBuilder();
    final MultipartEntity entity = new MultipartEntity();
    HttpPost request;

    // create the request
    builder.setScheme("http");
    builder.setHost("dev.bukkit.org");
    builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json");
    try {/*from ww  w .j  a  v a2 s . com*/
        entity.addPart("file_type", new StringBody(this.getFileType()));
        entity.addPart("name", new StringBody(this.project.getArtifact().getVersion()));
        entity.addPart("game_versions", new StringBody(gameVersion));
        entity.addPart("change_log", new StringBody(this.changeLog));
        entity.addPart("known_caveats", new StringBody(this.knownCaveats));
        entity.addPart("change_markup_type", new StringBody(this.markupType));
        entity.addPart("caveats_markup_type", new StringBody(this.markupType));
        entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact())));
    } catch (final UnsupportedEncodingException e) {
        throw new MojoExecutionException(e.getMessage());
    }

    // create the actual request
    try {
        request = new HttpPost(builder.build());
        request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0");
        request.setHeader("X-API-Key", this.key);
        request.setEntity(entity);
    } catch (final URISyntaxException exception) {
        throw new MojoExecutionException(exception.getMessage());
    }

    this.getLog().debug(request.toString());

    // send the request and handle any replies
    try {
        final HttpClient client = new DefaultHttpClient();
        final HttpResponse response = client.execute(request);
        switch (response.getStatusLine().getStatusCode()) {
        case 201:
            this.getLog().info("File uploaded successfully.");
            break;
        case 403:
            this.getLog().error(
                    "You have not specifed your API key correctly or do not have permission to upload to that project.");
            break;
        case 404:
            this.getLog().error("Project was not found. Either it is specified wrong or been renamed.");
            break;
        case 422:
            this.getLog().error("There was an error in uploading the plugin");
            this.getLog().debug(request.toString());
            this.getLog().debug(EntityUtils.toString(response.getEntity()));
            break;
        default:
            this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode());
            break;
        }
    } catch (final ClientProtocolException exception) {
        throw new MojoExecutionException(exception.getMessage());
    } catch (final IOException exception) {
        throw new MojoExecutionException(exception.getMessage());
    }

}