Example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

Introduction

In this page you can find the example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Prototype

HttpMultipartMode BROWSER_COMPATIBLE

To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Click Source Link

Usage

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public void postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String boundary = null;/*from w  ww . ja v  a2  s.  co m*/

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    //        Log.d("Debug", "JSONParser - command: " + command);

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = url + "gui/?action=start&hash=" + hash;
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = url + "gui/?action=pause&hash=" + hash;
    }

    if ("stop".equals(command) || "stopSelected".equals(command)) {
        url = url + "gui/?action=stop&hash=" + hash;
        Log.d("Debug", "Stoping torrent " + hash);
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {

        URI hash_uri = null;

        try {
            hash_uri = new URI(hash);
            hash = hash_uri.toString();

            //                Log.d("Debug","Torrent URL: "+ hash);

        } catch (URISyntaxException e) {
            Log.e("Debug", "URISyntaxException: " + e.toString());
        }

        url = url + "gui/?action=add-url&s=" + hash;
        //            key = "urls";
    }

    if ("addTorrentFile".equals(command)) {
        url = url + "gui/?action=add-file";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;
        //            urlContentType = "multipart/form-data";

    }

    //        if ("pauseall".equals(command)) {
    //            url = "command/pauseall";
    //        }
    //
    //        if ("pauseAll".equals(command)) {
    //            url = "command/pauseAll";
    //        }
    //
    //
    //        if ("resumeall".equals(command)) {
    //            url = "command/resumeall";
    //        }
    //
    //        if ("resumeAll".equals(command)) {
    //            url = "command/resumeAll";
    //        }

    if ("increasePrio".equals(command)) {
        url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("recheckSelected".equals(command)) {
        url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash=");
    }

    //        if ("toggleFirstLastPiecePrio".equals(command)) {
    //            url = "command/toggleFirstLastPiecePrio";
    //            key = "hashes";
    //
    //        }
    //
    //        if ("toggleSequentialDownload".equals(command)) {
    //            url = "command/toggleSequentialDownload";
    //            key = "hashes";
    //
    //        }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token;

        //            Log.d("Debug", "JSONParser - url: " + url);

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {
            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        // In order to pass the has we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Set content type and urls
        if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);

        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            //                Log.d("Debug", "JSONParser - urlContentType: " +  urlContentType);
            //                Log.d("Debug", "JSONParser - hash: " +  Uri.decode(URLEncoder.encode(hash, "UTF-8")));
            //                Log.d("Debug", "JSONParser - hash: " +  hash);

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null);
            //                builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

/**
 * attach log using run id// w  w w  . j a  v  a2  s .com
 * 
 * @param token
 *            - token generate using username and password
 * @param scope
 *            : project:release:cycle
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @param serviceUrl
 * @param scope
 * @return
 */
public int attachTestLogsUsingRunID(String serviceUrl, long testCaseRunId, File filePath, String scope) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate,
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId),
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public WebResponse multipartPostUrl(String sPage, boolean prefix, HashMap<String, ContentBody> nameValuePairs)
        throws UnsupportedEncodingException {
    WebResponse wr = null;/*from  w ww  . ja v  a  2 s . c  om*/
    String pageURL = (prefix ? this.urlBase + sPage : sPage);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }
    return doMultiPartPost(pageURL, entity);
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

/**
 * create HttpEntity for multi part file upload
 * @param file : file to upload, must be in class path
 * @param contentType/* w ww.j a  v a  2 s  .  c  o m*/
 * @return HttpEntity
 * @throws FileNotFoundException 
 */
private HttpEntity getMultiPartEntity(final File file, String formName) throws FileNotFoundException {
    InputStream is = null;
    if (file.exists()) {
        is = new FileInputStream(file);
    } else {
        LogHandler.warn("File not found, so trying to read it from class path now");
        is = HttpClient.class.getResourceAsStream(file.getPath());
    }
    if (null == formName) {
        formName = file.getName();
    }
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addBinaryBody(formName, is, ContentType.MULTIPART_FORM_DATA, file.getName());

    return builder.build();
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public WebResponse multipartPostUrl(String sPage, boolean prefix, List<BasicNameValuePair> nameValuePairs)
        throws UnsupportedEncodingException {
    WebResponse wr = null;/*www.  j a  v  a 2 s .c om*/
    String pageURL = (prefix ? this.urlBase + sPage : sPage);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (BasicNameValuePair nv : nameValuePairs) {
        entity.addPart(nv.getName(), new StringBody(nv.getValue()));
    }

    return this.doMultiPartPost(pageURL, entity);
    /*
    HttpPost webPost = new HttpPost(pageURL);
    webPost.setEntity(entity);
    HttpResponse response = null ;
    try {
    response = client.execute(webPost);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String sBody = responseHandler.handleResponse(response);
    wr = new WebResponse(response.getStatusLine().getStatusCode(), sBody);
    } catch (IOException ex) {
    log.error(ex.getMessage(), ex);
    } finally {
    if (response != null) {
        consumeContent(
            response.getEntity()
        );
    }
    }
    return wr; */
}

From source file:com.ibm.devops.dra.PublishTest.java

/**
 * * Send POST request to DLMS back end with the result file
 * @param bluemixToken - the Bluemix token
 * @param contents - the result file/*from  w w  w . j  av  a2 s. co  m*/
 * @param jobUrl -  the build url of the build job in Jenkins
 * @param timestamp
 * @return - response/error message from DLMS
 */
public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl,
        String timestamp) throws IOException {

    // create http client and post method
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(this.dlmsUrl);

    postMethod = addProxyInformation(postMethod);
    // build up multi-part forms
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (contents != null) {

        File file = new File(root, contents.getName());
        FileBody fileBody = new FileBody(file);
        builder.addPart("contents", fileBody);

        builder.addTextBody("test_artifact", file.getName());
        if (this.isDeploy) {
            builder.addTextBody("environment_name", environmentName);
        }
        //Todo check the value of lifecycleStage
        builder.addTextBody("lifecycle_stage", lifecycleStage);
        builder.addTextBody("url", jobUrl);
        builder.addTextBody("timestamp", timestamp);

        String fileExt = FilenameUtils.getExtension(contents.getName());
        String contentType;
        switch (fileExt) {
        case "json":
            contentType = CONTENT_TYPE_JSON;
            break;
        case "xml":
            contentType = CONTENT_TYPE_XML;
            break;
        default:
            return "Error: " + contents.getName() + " is an invalid result file type";
        }

        builder.addTextBody("contents_type", contentType);
        HttpEntity entity = builder.build();
        postMethod.setEntity(entity);
        postMethod.setHeader("Authorization", bluemixToken);
    } else {
        return "Error: File is null";
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(postMethod);
        // parse the response json body to display detailed info
        String resStr = EntityUtils.toString(response.getEntity());
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(resStr);

        if (!element.isJsonObject()) {
            // 401 Forbidden
            return "Error: Upload is Forbidden, please check your org name. Error message: "
                    + element.toString();
        } else {
            JsonObject resJson = element.getAsJsonObject();
            if (resJson != null && resJson.has("status")) {
                return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status");
            } else {
                // other cases
                return String.valueOf(response.getStatusLine());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Simple http post request. It needs an object to be sent. If an element of the object contains the key file then it will try to upload the resource indicated in the value as Uri ", example = "")
@APIParam(params = { "url", "params", "function(responseString)" })
public void httpPost(String url, Object object, final HttpPostCB callbackfn) {
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpContext localContext = new BasicHttpContext();
    final HttpPost httpPost = new HttpPost(url);

    Gson g = new Gson();
    JsonArray q = g.toJsonTree(object).getAsJsonArray();

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (int i = 0; i < q.size(); i++) {
        Set<Entry<String, JsonElement>> set = q.get(i).getAsJsonObject().entrySet();

        // go through elements
        String name = "";
        String content = "";
        String type = "";
        for (Object element : set) {
            Entry<String, JsonElement> entry = (Entry<String, JsonElement>) element;
            if (entry.getKey().equals("name")) {
                name = entry.getValue().getAsString();
            } else if (entry.getKey().equals("content")) {
                content = entry.getValue().getAsString();
            } else if (entry.getKey().equals("type")) {
                type = entry.getValue().getAsString();
            }/*from  ww w .j a va  2 s .  c o  m*/
        }

        // create the multipart
        if (type.contains("file")) {
            File f = new File(
                    ProjectManager.getInstance().getCurrentProject().getStoragePath() + "/" + content);
            ContentBody cbFile = new FileBody(f);
            entity.addPart(name, cbFile);
        } else if (type.contains("text")) { // Normal string data
            try {
                entity.addPart(name, new StringBody(content));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    // send
    httpPost.setEntity(entity);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                HttpResponse response = httpClient.execute(httpPost, localContext);
                callbackfn.event(response.getStatusLine().toString());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:com.lgallardo.qbittorrentclient.JSONParser.java

public String postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String limit = "";
    String tracker = "";

    String boundary = null;/*from   w  ww .  j  a v  a 2s .c  o  m*/

    String fileId = "";

    String filePriority = "";

    String result = "";

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    String label = "";

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = "command/resume";
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = "command/pause";
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = "command/delete";
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = "command/deletePerm";
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {
        url = "command/download";
        key = "urls";
    }

    if ("addTracker".equals(command)) {
        url = "command/addTrackers";
        key = "hash";

    }

    if ("addTorrentFile".equals(command)) {
        url = "command/upload";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;

    }

    if ("pauseall".equals(command)) {
        url = "command/pauseall";
    }

    if ("pauseAll".equals(command)) {
        url = "command/pauseAll";
    }

    if ("resumeall".equals(command)) {
        url = "command/resumeall";
    }

    if ("resumeAll".equals(command)) {
        url = "command/resumeAll";
    }

    if ("increasePrio".equals(command)) {
        url = "command/increasePrio";
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = "command/decreasePrio";
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = "command/topPrio";
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = "command/bottomPrio";
        key = "hashes";

    }

    if ("setFilePrio".equals(command)) {
        url = "command/setFilePrio";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];
        fileId = tmpString[1];
        filePriority = tmpString[2];

        //            Log.d("Debug", "hash: " + hash);
        //            Log.d("Debug", "fileId: " + fileId);
        //            Log.d("Debug", "filePriority: " + filePriority);
    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("setUploadRateLimit".equals(command)) {

        url = "command/setTorrentsUpLimit";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }
    }

    if ("setDownloadRateLimit".equals(command)) {
        url = "command/setTorrentsDlLimit";
        key = "hashes";

        Log.d("Debug", "Hash before: " + hash);

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }

        //            Log.d("Debug", "url: " + url);
        //            Log.d("Debug", "Hashes: " + hash + " | limit: " + limit);

    }

    if ("recheckSelected".equals(command)) {
        url = "command/recheck";
    }

    if ("toggleFirstLastPiecePrio".equals(command)) {
        url = "command/toggleFirstLastPiecePrio";
        key = "hashes";

    }

    if ("toggleSequentialDownload".equals(command)) {
        url = "command/toggleSequentialDownload";
        key = "hashes";

    }

    if ("toggleAlternativeSpeedLimits".equals(command)) {

        //            Log.d("Debug", "Toggling alternative rates");

        url = "command/toggleAlternativeSpeedLimits";
        key = "hashes";

    }

    if ("setLabel".equals(command)) {
        url = "command/setLabel";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("setCategory".equals(command)) {
        url = "command/setCategory";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("alternativeSpeedLimitsEnabled".equals(command)) {

        //            Log.d("Debug", "Getting alternativeSpeedLimitsEnabled");

        url = "command/alternativeSpeedLimitsEnabled";

        key = "hashes";
    }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        if ("addTracker".equals(command)) {

            String[] tmpString = hash.split("&");
            hash = tmpString[0];

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();

            try {
                tracker = tmpString[1];
            } catch (ArrayIndexOutOfBoundsException e) {
                tracker = "";
            }

            //                Log.d("Debug", "addTracker - hash: " + hash);
            //                Log.d("Debug", "addTracker - tracker: " + tracker);

        }

        // In order to pass the hash we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        // Add limit
        if (!limit.equals("")) {
            Log.d("Debug", "JSONParser - Limit: " + limit);
            nvps.add(new BasicNameValuePair("limit", limit));
        }

        // Set values for setting file priority
        if ("setFilePrio".equals(command)) {

            nvps.add(new BasicNameValuePair("id", fileId));
            nvps.add(new BasicNameValuePair("priority", filePriority));
        }

        // Add label
        if (label != null && !label.equals("")) {

            label = Uri.decode(label);

            if ("setLabel".equals(command)) {

                nvps.add(new BasicNameValuePair("label", label));
            } else {

                nvps.add(new BasicNameValuePair("category", label));
            }

            //                Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<");
        }

        // Add tracker
        if (tracker != null && !tracker.equals("")) {

            nvps.add(new BasicNameValuePair("urls", tracker));

            //                Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<");

        }

        String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8);

        // This replaces encoded char "+" for "%20" so spaces can be passed as parameter
        entityValue = entityValue.replaceAll("\\+", "%20");

        StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
        stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);

        httpget.setEntity(stringEntity);

        // Set content type and urls
        if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command)
                || "maxPrio".equals(command) || "setFilePrio".equals(command)
                || "toggleAlternativeSpeedLimits".equals(command)
                || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command)
                || "setCategory".equals(command) || "addTracker".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);
        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        //            Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode);

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        result = EntityUtils.toString(httpEntity);

        //            Log.d("Debug", "JSONPArser - command result: " + result);

        return result;

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (SSLPeerUnverifiedException e) {
        Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString());
        throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE);
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return null;

}

From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java

public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;/*from ww w.  j a  va2s. c o  m*/
    org.apache.http.HttpResponse response = null;
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpPost httppost = new HttpPost(this.endpoint);
        httppost.setConfig(requestConfig);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart(PARAM_NAME_CHANGE_ICON, new FileBody(appIcon));
        builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_HASH_ID,
                new StringBody(applicationHash, ContentType.TEXT_PLAIN));
        httppost.setEntity(builder.build());
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            throw new AppCloudIntegrationTestException("Update app icon failed " + result);
        }
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // And this will be asserted so if it failed due to a valid case, it will be captured.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke app icon update API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}