Example usage for org.apache.http.impl.client HttpClients createDefault

List of usage examples for org.apache.http.impl.client HttpClients createDefault

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients createDefault.

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:com.zhuc.nupay.mcm.app.jbei.HttpApi.java

public String post(String url, List<NameValuePair> params) throws HttpApiException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(url);
    //        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    //        nvps.add(new BasicNameValuePair("username", "admin"));
    //        nvps.add(new BasicNameValuePair("password", "admin"));
    //        // post?

    CloseableHttpResponse response = null;
    try {/*from   ww  w.j a  va 2  s .co  m*/
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // ??
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            InputStream is = entity.getContent();
            // inputstreamreader???
            BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }

            is.close();
            //System.out.println(":->"+sb.toString());

            return sb.toString();
        } else {
            throw new HttpApiException("Empty Response from server");
        }

    } catch (IOException ex) {
        Logger.getLogger(HttpApi.class.getName()).log(Level.SEVERE, null, ex);

        throw new HttpApiException("Network Error", ex);

    } finally {
        try {
            if (response != null)
                response.close();
        } catch (IOException ex) {
            Logger.getLogger(HttpApi.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:es.uned.dia.jcsombria.softwarelinks.transport.HttpTransport.java

public Object send(String request) throws Exception {
    Object response = null;// w ww  . ja v  a  2 s . c  om
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverURL.toString());
        httppost.setEntity(new StringEntity(request));
        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = responseBody;
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:at.kc.tugraz.ss.main.SSMediaWikiWithLDAP.java

public SSMediaWikiWithLDAP() throws Exception {

    final HttpClient httpclient = HttpClients.createDefault();
    final String token = loginFirstTime(httpclient);
    final String sessionID = loginSecondTime(httpclient, token);
    String content = queryContent(httpclient, sessionID, "MyFirstVorgang");

    changeContent(httpclient, sessionID, "MyFirstVorgang");

    content = queryContent(httpclient, sessionID, "MyFirstVorgang");

    logout(httpclient);/*from  w  w  w  .  j a  v a2s . c om*/
}

From source file:nl.salp.warcraft4j.io.HttpDataReader.java

public HttpDataReader(String url) throws DataParsingException {
    try {/*from  ww w .  j  a v a 2  s  .co  m*/
        httpClient = HttpClients.createDefault();
        response = httpClient.execute(new HttpGet(URI.create(url)));
        responseStream = getResponseStream(url, response);
    } catch (Exception e) {
        try {
            close();
        } catch (IOException ioe) {
            // Ignore.
        }
        throw new DataParsingException(e);
    }
}

From source file:org.openo.nfvo.monitor.umc.monitor.common.HttpClientUtil.java

/**
 * @Title httpDelete/*from ww w  . j a  v  a2 s  .c o m*/
 * @Description TODO(realize the rest interface to access by httpDelete)
 * @param url
 * @return
 * @throws Exception
 * @return int (return StatusCode,If zero error said)
 */
public static int httpDelete(String url) throws Exception {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(url);
    try {
        CloseableHttpResponse res = httpClient.execute(httpDelete);
        try {
            return res.getStatusLine().getStatusCode();
        } finally {
            res.close();
        }
    } catch (ParseException e) {
        LOGGER.error("HttpClient throw ParseException:" + url, e);
    } catch (IOException e) {
        LOGGER.error("HttpClient throw IOException:" + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.error("HttpClient Close throw IOException", e);
        }
    }

    return 0;

}

From source file:io.github.discovermovies.datacollector.movie.network.TheMovieDbApi.java

public TheMovieDbApi() {
    client = HttpClients.createDefault();
    apiKey = properties.getProperty("Key");
    apiKey = apiKey == null ? "" : apiKey;
    String apiLogFileName = properties.getProperty(Application.KEY_LIST[ConfigValues.APT_LOG]);
    String apiErrorLogName = properties.getProperty(Application.KEY_LIST[ConfigValues.API_ERR_LOG]);
    log = new Logger(apiLogFileName, false, false);
    errLog = new Logger(apiErrorLogName, true, true);
}

From source file:de._692b8c32.cdlauncher.tasks.GoogleDownloadTask.java

@Override
public void doWork() {
    setProgress(-1);//from ww  w  .j a  va2 s .  c o  m

    try {
        HttpClient client = HttpClients.createDefault();
        String realUrl = null;
        Pattern pattern = Pattern.compile(
                "<a id=\"uc-download-link\" class=\"goog-inline-block jfk-button jfk-button-action\" href=\"([^\"]*)\">");
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(client.execute(new HttpGet(fileUrl)).getEntity().getContent()))) {
            for (String line : reader.lines().collect(Collectors.toList())) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    realUrl = fileUrl.substring(0, fileUrl.lastIndexOf('/'))
                            + matcher.group(1).replace("&amp;", "&");
                    break;
                }
            }
        }

        if (realUrl == null) {
            throw new RuntimeException("Failed to find real url");
        } else {
            try (InputStream stream = client.execute(new HttpGet(realUrl)).getEntity().getContent()) {
                Files.copy(stream, cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException("Could not download data", ex);
    }
}

From source file:es.uned.dia.jcsombria.model_elements.softwarelinks.nodejs.HttpTransport.java

public Object send(String request) throws Exception {
    Object response = null;// w ww  .  j a  v a  2  s  . com
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverURL.toString());
        System.out.println("Executing request " + httppost.getRequestLine());
        System.out.println(request);
        httppost.setEntity(new StringEntity(request));
        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = responseBody;
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:com.wattzap.model.social.SelfLoopsAPI.java

public static int uploadActivity(String email, String passWord, String fileName, String note)
        throws IOException {
    JSONObject jsonObj = null;//from   w ww  .  j  a  v a 2  s. c o m

    FileInputStream in = null;
    GZIPOutputStream out = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("enctype", "multipart/mixed");

        in = new FileInputStream(fileName);
        // Create stream to compress data and write it to the to file.
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        out = new GZIPOutputStream(obj);

        // Copy bytes from one stream to the other
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytes_read);
        }
        out.close();
        in.close();

        ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"),
                fileName);
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN))
                .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin)
                .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build();

        httpPost.setEntity(reqEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            switch (code) {
            case 200:

                HttpEntity respEntity = response.getEntity();

                if (respEntity != null) {
                    // EntityUtils to get the response content
                    String content = EntityUtils.toString(respEntity);
                    //System.out.println(content);
                    JSONParser jsonParser = new JSONParser();
                    jsonObj = (JSONObject) jsonParser.parse(content);
                }

                break;
            case 403:
                throw new RuntimeException(
                        "Authentification failure " + email + " " + response.getStatusLine());
            default:
                throw new RuntimeException("Error " + code + " " + response.getStatusLine());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }

        int activityId = ((Long) jsonObj.get("activity_id")).intValue();

        // parse error code
        int error = ((Long) jsonObj.get("error_code")).intValue();
        if (activityId == -1) {
            String message = (String) jsonObj.get("message");
            switch (error) {
            case 102:
                throw new RuntimeException("Empty TCX file " + fileName);
            case 103:
                throw new RuntimeException("Invalide TCX Format " + fileName);
            case 104:
                throw new RuntimeException("TCX Already Present " + fileName);
            case 105:
                throw new RuntimeException("Invalid XML " + fileName);
            case 106:
                throw new RuntimeException("invalid compression algorithm");
            case 107:
                throw new RuntimeException("Invalid file mime types");
            default:
                throw new RuntimeException(message + " " + error);
            }
        }

        return activityId;
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        httpClient.close();
    }
}

From source file:net.yoomai.virgo.spider.Emulator.java

/**
 * //from w w w.  j  a  va2  s . c o  m
 *
 * @param params
 * @param url
 */
public String login(Map<String, String> params, String url) {
    String cookie = "";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = generateURLParams(params);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    if (response != null) {
        StatusLine statusLine = response.getStatusLine();
        log.info(statusLine);
        if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 302) {
            Header[] headers = response.getHeaders("Set-Cookie");
            for (Header header : headers) {
                cookie += header.getValue() + ";";
            }
        }
    }

    return cookie;
}