List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine
StatusLine getStatusLine();
From source file:com.lagrange.LabelApp.java
/** * Try to send message with labels and its probabilities to telegram *//*from ww w . ja v a 2s . c om*/ private static void sendMessageToTelegramBot(List<EntityAnnotation> labels) throws IOException { String urlSendMessage = "https://api.telegram.org/" + BOT_ID + "/sendMessage"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(urlSendMessage); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("text", buildMessage(labels))); nvps.add(new BasicNameValuePair("chat_id", CHAT_ID)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println(response.getStatusLine()); } finally { response.close(); } System.out.println("Done sending text"); }
From source file:org.rapidoid.http.HTTP.java
public static byte[] post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files) throws IOException, ClientProtocolException { headers = U.safe(headers);/* www. j a v a 2 s . co m*/ data = U.safe(data); files = U.safe(files); CloseableHttpClient client = client(uri); try { HttpPost httppost = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { ContentType contentType = ContentType.create("application/octet-stream"); String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, contentType, filename); } for (Entry<String, String> entry : data.entrySet()) { ContentType contentType = ContentType.create("text/plain", "UTF-8"); builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType); } httppost.setEntity(builder.build()); for (Entry<String, String> e : headers.entrySet()) { httppost.addHeader(e.getKey(), e.getValue()); } Log.info("Starting HTTP POST request", "request", httppost.getRequestLine()); CloseableHttpResponse response = client.execute(httppost); try { int statusCode = response.getStatusLine().getStatusCode(); U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode); InputStream resp = response.getEntity().getContent(); return IOUtils.toByteArray(resp); } finally { response.close(); } } finally { client.close(); } }
From source file:org.lokra.seaweedfs.util.ConnectionUtil.java
/** * Check uri link is alive, the basis for judging response status code. * * @param client httpClient//from ww w .ja va 2s .co m * @param url check url * @return When the response status code is 200, the result is true. */ public static boolean checkUriAlive(CloseableHttpClient client, String url) { boolean result = false; CloseableHttpResponse response = null; HttpGet request = new HttpGet(url); try { response = client.execute(request, HttpClientContext.create()); result = response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (IOException e) { return false; } finally { if (response != null) { try { response.close(); } catch (IOException ignored) { } } request.releaseConnection(); } return result; }
From source file:org.eclipse.dirigible.cli.apis.ImportProjectAPI.java
private static void executeRequest(CloseableHttpClient httpClient, HttpPost postRequest) throws IOException, ClientProtocolException { try {//from w w w . java2 s .c o m CloseableHttpResponse response = httpClient.execute(postRequest); try { logger.log(Level.INFO, "----------------------------------------"); logger.log(Level.INFO, response.getStatusLine().toString()); HttpEntity resultEntity = response.getEntity(); if (resultEntity != null) { logger.log(Level.INFO, "Response content length: " + resultEntity.getContentLength()); } EntityUtils.consume(resultEntity); } finally { response.close(); } } finally { httpClient.close(); } }
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 w w.j ava2 s . 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:com.hazelcast.test.starter.HazelcastVersionLocator.java
private static File downloadFile(String url, File targetDirectory, String filename) { CloseableHttpClient client = HttpClients.createDefault(); File targetFile = new File(targetDirectory, filename); if (targetFile.isFile() && targetFile.exists()) { return targetFile; }/*from w w w .ja v a 2s.com*/ HttpGet request = new HttpGet(url); try { CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != SC_OK) { throw new GuardianException("Cannot download file from " + url + ", http response code: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); FileOutputStream fos = new FileOutputStream(targetFile); entity.writeTo(fos); fos.close(); targetFile.deleteOnExit(); return targetFile; } catch (IOException e) { throw rethrowGuardianException(e); } finally { try { client.close(); } catch (IOException e) { // ignore } } }
From source file:org.sead.repositories.reference.util.SEADAuthenticator.java
static public HttpClientContext authenticate(String server) { boolean authenticated = false; log.info("Authenticating"); String accessToken = SEADGoogleLogin.getAccessToken(); // Now login to server and create a session CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from w w w. j a v a 2 s .c om*/ // //DoLogin is the auth endpoint when using the AUthFilter, versus // the api/authenticate endpoint when connecting to the ACR directly HttpPost seadAuthenticate = new HttpPost(server + "/DoLogin"); List<NameValuePair> nvpList = new ArrayList<NameValuePair>(1); nvpList.add(0, new BasicNameValuePair("googleAccessToken", accessToken)); seadAuthenticate.setEntity(new UrlEncodedFormEntity(nvpList)); CloseableHttpResponse response = httpclient.execute(seadAuthenticate, localContext); try { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // String seadSessionId = // EntityUtils.toString(resEntity); authenticated = true; } } else { // Seems to occur when google device id is not set on server // - with a Not Found response... log.error("Error response from " + server + " : " + response.getStatusLine().getReasonPhrase()); } } finally { response.close(); httpclient.close(); } } catch (IOException e) { log.error("Cannot read sead-google.json"); log.error(e.getMessage()); } // localContext should have the cookie with the SEAD session key, which // nominally is all that's needed. // FixMe: If there is no activity for more than 15 minutes, the session // may expire, in which case, // re-authentication using the refresh token to get a new google token // to allow SEAD login again may be required // also need to watch the 60 minutes google token timeout - project // spaces will invalidate the session at 60 minutes even if there is // activity authTime = System.currentTimeMillis(); if (authenticated) { return localContext; } return null; }
From source file:lh.api.showcase.server.util.HttpQueryUtils.java
public static String executeQuery(URI uri, ApiAuth apiAuth, HasProxySettings proxySetting, HttpClientFactory httpClientFactory, final int maxRetries) throws HttpErrorResponseException { //logger.info("uri: " + uri.toString()); AtomicInteger tryCounter = new AtomicInteger(0); while (true) { CloseableHttpClient httpclient = httpClientFactory.getHttpClient(proxySetting); HttpGet httpGet = new HttpGet(uri); httpGet.addHeader("Authorization", apiAuth.getAuthHeader()); httpGet.addHeader("Accept", "application/json"); //logger.info("auth: " + apiAuth.getAuthHeader()) ; //logger.info("query: " + httpGet.toString()); CloseableHttpResponse response = null; try {//from ww w. j a va 2s. com response = httpclient.execute(httpGet); StatusLine status = response.getStatusLine(); BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); String json = IOUtils.toString(entity.getContent(), "UTF8"); EntityUtils.consume(entity); //logger.info("response: " + json); // check for errors if (status != null && status.getStatusCode() > 299) { if (status.getStatusCode() == 401) { // token has probably expired logger.info("Authentication Error. Token will be refreshed"); if (tryCounter.getAndIncrement() < maxRetries) { if (apiAuth.updateAccessToken()) { logger.info("Token successfully refreshed"); // we retry with the new token logger.info("Retry number " + tryCounter.get()); continue; } } } throw new HttpErrorResponseException(status.getStatusCode(), status.getReasonPhrase(), json); } return json; } catch (IOException e) { logger.severe(e.getMessage()); break; } finally { try { if (response != null) { response.close(); } } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage()); } } } return null; }
From source file:com.aws.sampleImage.url.TestHttpGetFlickrAPIProfile.java
private static String callFlickrAPIForEachKeyword(String query) throws IOException, JSONException { String apiKey = "ad4f88ecfd53b17f93178e19703fe00d"; String apiSecret = "96cab0e9f89468d6"; long httpCallTime = 0L; long jsonParseTime = 0L; int totalPages = 4; int total = 500; int perPage = 500; int counter = 0; int currentCount = 0; for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) { long startHttpCall = System.currentTimeMillis(); String url = "https://api.flickr.com/services/rest/?method=flickr.photos.search&text=" + query + "&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=" + i + "&format=json&api_key=" + apiKey + "&api_secret=" + apiSecret + "&license=4,5,6,7,8"; System.out.println("URL FORMED --> " + url); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode()); long endHttpCall = System.currentTimeMillis(); httpCallTime = (long) (httpCallTime + (long) (endHttpCall - startHttpCall)); long startJsonParse = System.currentTimeMillis(); BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine;//from ww w . j a v a 2 s.c om StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); String responseString = response.toString(); responseString = responseString.replace("jsonFlickrApi(", ""); int length = responseString.length(); responseString = responseString.substring(0, length - 1); // print result System.out.println("After making it a valid JSON --> " + responseString); httpClient.close(); JSONObject json = null; try { json = new JSONObject(responseString); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("Converted JSON String " + json); JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null; total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0; perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0; System.out.println(" perPage --> " + perPage + " total --> " + total); JSONArray photoArr = photosObj.getJSONArray("photo"); System.out.println("Length of Array --> " + photoArr.length()); String scrapedImageURL = ""; for (int itr = 0; itr < photoArr.length(); itr++) { JSONObject tempObject = photoArr.getJSONObject(itr); scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c") : tempObject.has("url_m") ? tempObject.getString("url_m") : tempObject.has("url_n") ? tempObject.getString("url_n") : ""; //System.out.println("Scraped Image URL --> " + scrapedImageURL); counter++; } long endJsonParse = System.currentTimeMillis(); jsonParseTime = (long) (jsonParseTime + (long) (endJsonParse - startJsonParse)); } System.out.println("C O U N T E R -> " + counter); System.out.println("HTTP CALL TIME --> " + httpCallTime + " JSON PARSE TIME --> " + jsonParseTime); return null; }
From source file:eu.ebbitsproject.peoplemanager.utils.HttpUtils.java
public static void postData(String url, String action, String errorType, String objectId, String personId, String eventId) {/*from w w w. ja v a2 s.com*/ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("action", action)); nvps.add(new BasicNameValuePair("personId", personId)); nvps.add(new BasicNameValuePair("errorType", errorType)); nvps.add(new BasicNameValuePair("objectId", objectId)); nvps.add(new BasicNameValuePair("eventId", eventId)); System.out.println("action = " + action); System.out.println("personId = " + personId); System.out.println("errorType = " + errorType); System.out.println("objectId = " + objectId); System.out.println("eventId = " + eventId); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } catch (UnsupportedEncodingException ex) { Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex); } CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } catch (IOException e) { Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e); } finally { try { response.close(); } catch (IOException e) { Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e); } } }