List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:com.mywork.framework.util.RemoteHttpUtil.java
/** * ?MultipartHttp??????ContentBody map/*ww w .j a va2 s . co m*/ */ public static String fetchMultipartHttpResponse(String contentUrl, Map<String, String> headerMap, Map<String, ContentBody> bodyMap) throws IOException { try { HttpPost httpPost = new HttpPost(contentUrl); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (headerMap != null && !headerMap.isEmpty()) { for (Map.Entry<String, String> m : headerMap.entrySet()) { httpPost.addHeader(m.getKey(), m.getValue()); } } if (bodyMap != null && !bodyMap.isEmpty()) { for (Map.Entry<String, ContentBody> m : bodyMap.entrySet()) { multipartEntityBuilder.addPart(m.getKey(), m.getValue()); } } HttpEntity reqEntity = multipartEntityBuilder.build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity resEntity = response.getEntity(); String resStr = IOUtils.toString(resEntity.getContent()); return resStr; } catch (Exception e) { // TODO: handle exception } finally { response.close(); } } finally { httpClient.close(); } return null; }
From source file:com.cht.imserver.push.TLPushNotification.java
public static PNResult pushMessage_iOS(String token, String message, String lockey, String locargs, String sound, int badge, String licenseKey, PNServerType type, String proxy, int port) throws IOException, UnsupportedEncodingException, ClientProtocolException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpHost httpproxy = null;//from w w w . ja va 2 s . co m String serverURL = null; PNResult result = null; if (type == PNServerType.ios_dev) { serverURL = deviOSHost; } else if (type == PNServerType.ios_official) { serverURL = officeialiOSHost; } String jsontoken = "{\"iosTokens\":[{\"token\":\"" + token + "\",\"badge\" : " + String.valueOf(badge) + "}]}"; String jsonmessage = null; if (lockey == null || "".equals(lockey)) { jsonmessage = "{\"message\":\"" + message + "\",\"sound\":\"" + sound + "\"}"; } else { jsonmessage = "{\"message\":\"" + message + "\",\"sound\":\"" + sound + "\",\"loc-key\":\"" + lockey + "\",\"loc-args\":" + locargs + "}"; } //System.out.println("iosdata=" + jsonmessage); //System.out.println("iostoken=" + jsontoken); //logger.info("jsonmessage:" + jsonmessage + ", jsontoken:" + jsontoken + ", licenseKey:" + licenseKey ); logger.info("jsonmessage:" + jsonmessage + ", licenseKey:" + licenseKey); try { HttpPost httpPost = new HttpPost(serverURL); if (proxy != null) { httpproxy = new HttpHost(proxy, port); RequestConfig config = RequestConfig.custom().setProxy(httpproxy).build(); httpPost.setConfig(config); } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("iosdata", jsonmessage)); nvps.add(new BasicNameValuePair("iostoken", jsontoken)); nvps.add(new BasicNameValuePair("licensekey", licenseKey)); nvps.add(new BasicNameValuePair("appname", appname)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); //System.out.println(EntityUtils.toString(httpPost.getEntity()) ); CloseableHttpResponse response2 = httpclient.execute(httpPost); Gson mGson = new Gson(); try { //System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); //System.out.println(EntityUtils.toString(entity2)); result = mGson.fromJson(EntityUtils.toString(entity2), PNResult.class); EntityUtils.consume(entity2); } finally { response2.close(); } } finally { httpclient.close(); } return result; }
From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java
/** * Send request by post method.//from w w w. j a va2 s . co m * * @param uri: * http://ip:port/demo */ public static String doPostJson(String uri, String data) { String result = ""; try { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.setEntity(new StringEntity(data, ContentType.create("text/json", "UTF-8"))); client = HttpClients.createDefault(); response = client.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } finally { if (response != null) { response.close(); } if (client != null) { client.close(); } } } catch (Exception e) { e.printStackTrace(); LOG.error("Do post json request has error, msg is " + e.getMessage()); } return result; }
From source file:org.drftpd.util.HttpUtils.java
public static String retrieveHttpAsString(String url) throws HttpException, IOException { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000) .setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig) .setUserAgent(_userAgent).build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig);//from w ww . ja va 2s . c om CloseableHttpResponse response = null; try { response = httpclient.execute(httpGet); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new HttpException("Error " + statusCode + " for URL " + url); } HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); EntityUtils.consume(entity); return data; } catch (IOException e) { throw new IOException("Error for URL " + url, e); } finally { if (response != null) { response.close(); } httpclient.close(); } }
From source file:com.caibowen.gplume.misc.test.HttpClientUtil.java
/** * HTTPS/*from w ww.j a v a2 s . com*/ * * @param url * @param params * @return */ public static String post(String url, Map<String, String> params, int connectTimeout, Charset charset) { final HttpPost httpPost = new HttpPost(url); httpPost.setConfig(buildConfig(connectTimeout, connectTimeout)); try { setParam(httpPost, params, charset); final CloseableHttpResponse response = httpClient.execute(httpPost); try { // POST final HttpEntity entity = response.getEntity(); // ?? if (null != entity) return EntityUtils.toString(entity, charset); } catch (Exception e) { logger.error("[HttpUtils Post] get response error, url:" + url, e); } finally { if (response != null) response.close(); } } catch (ClientProtocolException e) { logger.error("[HttpUtils Post] invoke timeout, url=" + url, e); } catch (Exception e) { logger.error("[HttpUtils Post] invoke error, url=" + url, e); } finally { httpPost.releaseConnection(); } return null; }
From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java
public static HTTPResponseData sendGet(String url, String username, String pwd) throws Exception { CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build(); int responseCode = 0; StringBuffer respo = null;/* w ww.j a v a 2 s . c o m*/ String userPassword = username + ":" + pwd; // String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes()); String encoding = Base64.encodeBase64String(userPassword.getBytes()); try { HttpGet request = new HttpGet(url); request.addHeader("Authorization", "Basic " + encoding); request.addHeader("User-Agent", USER_AGENT); System.out.println("Executing request " + request.getRequestLine()); CloseableHttpResponse response = client.execute(request); try { responseCode = response.getStatusLine().getStatusCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); respo = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { respo.append(inputLine); } } finally { response.close(); } } finally { client.close(); } HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString())); System.out.println(result.getStatusCode() + "/n" + result.getBody()); return result; }
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession createSession(final String username, String password) throws ScratchLoginException { try {/* w w w . j a v a2s. c o m*/ final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/") .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu") .addHeader("X-Requested-With", "XMLHttpRequest").build(); resp = httpClient.execute(csrf); resp.close(); String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); final JSONObject loginObj = new JSONObject(); loginObj.put("username", username); loginObj.put("password", password); loginObj.put("captcha_challenge", ""); loginObj.put("captcha_response", ""); loginObj.put("embed_captcha", false); loginObj.put("timezone", "America/New_York"); loginObj.put("csrfmiddlewaretoken", csrfToken); final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("X-CSRFToken", csrfToken).setEntity(new StringEntity(loginObj.toString())).build(); resp = httpClient.execute(login); password = null; final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONObject jsonOBJ = new JSONObject( result.toString().substring(1, result.toString().length() - 1)); if ((int) jsonOBJ.get("success") != 1) throw new ScratchLoginException(); String ssi = null; String sct = null; String e = null; final Header[] headers = resp.getAllHeaders(); for (final Header header : headers) if (header.getName().equals("Set-Cookie")) { final String value = header.getValue(); final String[] split = value.split(Pattern.quote("; ")); for (final String s : split) { if (s.contains("=")) { final String[] split2 = s.split(Pattern.quote("=")); final String key = split2[0]; final String val = split2[1]; if (key.equals("scratchsessionsid")) ssi = val; else if (key.equals("scratchcsrftoken")) sct = val; else if (key.equals("expires")) e = val; } } } resp.close(); return new ScratchSession(ssi, sct, e, username); } catch (final IOException e) { e.printStackTrace(); throw new ScratchLoginException(); } }
From source file:com.caibowen.gplume.misc.test.HttpClientUtil.java
public static byte[] getBytes(String url, Map<String, String> params, int connectTimeout) { final String uri = setParam(url, params, Consts.UTF_8); final HttpGet get = new HttpGet(uri); get.setConfig(buildConfig(connectTimeout, connectTimeout)); try {/* w ww . j a v a 2 s. c o m*/ final CloseableHttpResponse response = httpClient.execute(get); try { final HttpEntity entity = response.getEntity(); if (entity.getContentLength() > 0) return EntityUtils.toByteArray(entity); logger.error("[HttpUtils Get]get content error,content=" + EntityUtils.toString(entity)); } catch (Exception e) { logger.error(String.format("[HttpUtils Get]get response error, url:%s", uri), e); } finally { if (response != null) response.close(); } } catch (SocketTimeoutException e) { logger.error(String.format("[HttpUtils Get]invoke get timeout error, url:%s", uri), e); } catch (Exception e) { logger.error(String.format("[HttpUtils Get]invoke get error, url:%s", uri), e); } finally { get.releaseConnection(); } return null; }
From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java
public static void upload(String url, String playerName, File jsonfile, File sourcefile) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//w ww.j a va 2s. c o m HttpPost httppost = new HttpPost(url); FileBody json = new FileBody(jsonfile); FileBody source = new FileBody(sourcefile); String jsontext = readFromFile(jsonfile); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN)) .addPart("jsonfile", json).addPart("sourcefile", source) .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN)) .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext", new StringBody("public class Foo {\n int x=5\n}", ContentType.TEXT_PLAIN)) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { //System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { //System.out.println("Response content length: " + resEntity.getContentLength()); Scanner sc = new Scanner(resEntity.getContent()); while (sc.hasNext()) { System.out.println(sc.nextLine()); } sc.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } finally { httpclient.close(); } }
From source file:DeliverWork.java
private static String getResultBody(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String resultBody = null;//from w w w . j a v a 2 s . c o m try { httpClient = HttpClients.createDefault(); // http(get?) HttpGet httpget = new HttpGet(url); response = httpClient.execute(httpget); HttpEntity result = response.getEntity(); resultBody = EntityUtils.toString(result); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return resultBody; }