List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.github.dfa.diaspora_android.task.GetPodsService.java
private void getPods() { /*/*from ww w . ja va 2 s . co m*/ * Most of the code in this AsyncTask is from the file getPodlistTask.java * from the app "Diaspora Webclient". * A few modifications and adaptations were made by me. * Source: * https://github.com/voidcode/Diaspora-Webclient/blob/master/src/com/voidcode/diasporawebclient/getPodlistTask.java * Thanks to Terkel Srensen ; License : GPLv3 */ AsyncTask<Void, Void, String[]> getPodsAsync = new AsyncTask<Void, Void, String[]>() { @Override protected String[] doInBackground(Void... params) { // TODO: Update deprecated code StringBuilder builder = new StringBuilder(); //HttpClient client = new DefaultHttpClient(); List<String> list = null; HttpsURLConnection connection; InputStream inStream; try { connection = NetCipher .getHttpsURLConnection("https://podupti.me/api.php?key=4r45tg&format=json"); int statusCode = connection.getResponseCode(); if (statusCode == 200) { inStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } try { inStream.close(); } catch (IOException e) { /*Nothing to do*/} connection.disconnect(); } else { AppLog.e(this, "Failed to download list of pods"); } } catch (IOException e) { //TODO handle json buggy feed e.printStackTrace(); } //Parse the JSON Data try { JSONObject jsonObjectAll = new JSONObject(builder.toString()); JSONArray jsonArrayAll = jsonObjectAll.getJSONArray("pods"); AppLog.d(this, "Number of entries " + jsonArrayAll.length()); list = new ArrayList<>(); for (int i = 0; i < jsonArrayAll.length(); i++) { JSONObject jo = jsonArrayAll.getJSONObject(i); if (jo.getString("secure").equals("true")) list.add(jo.getString("domain")); } } catch (Exception e) { //TODO Handle Parsing errors here e.printStackTrace(); } if (list != null) return list.toArray(new String[list.size()]); else return null; } @Override protected void onPostExecute(String[] pods) { Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED); broadcastIntent.putExtra("pods", pods != null ? pods : new String[0]); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent); stopSelf(); } }; getPodsAsync.execute(); }
From source file:org.schabi.newpipe.Downloader.java
/** AsyncTask impl: executed in background thread does the download */ @Override/* ww w . j a va2 s. c o m*/ protected Void doInBackground(Void... voids) { HttpsURLConnection con = null; InputStream inputStream = null; FileOutputStream outputStream = null; try { con = NetCipher.getHttpsURLConnection(fileURL); int responseCode = con.getResponseCode(); // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { fileSize = con.getContentLength(); inputStream = new BufferedInputStream(con.getInputStream()); outputStream = new FileOutputStream(saveFilePath); int bufferSize = 8192; int downloaded = 0; int bytesRead = -1; byte[] buffer = new byte[bufferSize]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); downloaded += bytesRead; if (downloaded % 50000 < bufferSize) { publishProgress(downloaded); } } publishProgress(bufferSize); } else { Log.i(TAG, "No file to download. Server replied HTTP code: " + responseCode); } } catch (IOException e) { Log.e(TAG, "No file to download. Server replied HTTP code: ", e); e.printStackTrace(); } finally { try { if (outputStream != null) { outputStream.close(); outputStream = null; } if (inputStream != null) { inputStream.close(); inputStream = null; } } catch (IOException e) { e.printStackTrace(); } if (con != null) { con.disconnect(); con = null; } } return null; }
From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java
@Test public void putGetFileExample() throws Exception { HttpsURLConnection connection; String redirect;//w ww.j a v a 2 s. c o m InputStream input; OutputStream output; String data = UUID.randomUUID().toString(); connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=CREATE"); connection.setRequestMethod("PUT"); assertThat(connection.getResponseCode(), is(307)); redirect = connection.getHeaderField("Location"); connection.disconnect(); connection = createHttpUrlConnection(redirect); connection.setRequestMethod("PUT"); connection.setDoOutput(true); output = connection.getOutputStream(); IOUtils.write(data.getBytes(), output); output.close(); connection.disconnect(); assertThat(connection.getResponseCode(), is(201)); connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=OPEN"); assertThat(connection.getResponseCode(), is(307)); redirect = connection.getHeaderField("Location"); connection.disconnect(); connection = createHttpUrlConnection(redirect); input = connection.getInputStream(); assertThat(IOUtils.toString(input), is(data)); input.close(); connection.disconnect(); }
From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java
public void executeDownloadFileRequest(File filename) throws MarketoException { String err;/* w w w .j a v a 2s. co m*/ try { URL url = new URL(current_uri.toString()); HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection(); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("accept", "text/json"); int responseCode = urlConn.getResponseCode(); if (responseCode == 200) { InputStream inStream = urlConn.getInputStream(); FileUtils.copyInputStreamToFile(inStream, filename); } else { err = String.format("Download failed for %s. Status: %d", filename, responseCode); throw new MarketoException(REST, err); } } catch (IOException e) { err = String.format("Download failed for %s. Cause: %s", filename, e.getMessage()); LOG.error(err); throw new MarketoException(REST, err); } }
From source file:com.wso2telco.MePinStatusRequest.java
public String call() { String allowStatus = null;/*w w w . ja v a 2 s. c o m*/ String clientId = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig() .getMePinClientId(); String url = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig() .getMePinUrl(); url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId + ""; if (log.isDebugEnabled()) { log.info("MePIN Status URL : " + url); } String authHeader = "Basic " + configurationService.getDataHolder().getMobileConnectConfig() .getSessionUpdaterConfig().getMePinAccessToken(); try { HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", authHeader); String resp = ""; int statusCode = connection.getResponseCode(); InputStream is; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { resp += output; } br.close(); if (log.isDebugEnabled()) { log.debug("MePIN Status Response Code : " + statusCode + " " + connection.getResponseMessage()); log.debug("MePIN Status Response : " + resp); } JsonObject responseJson = new JsonParser().parse(resp).getAsJsonObject(); String respTransactionId = responseJson.getAsJsonPrimitive("transaction_id").getAsString(); JsonPrimitive allowObject = responseJson.getAsJsonPrimitive("allow"); if (allowObject != null) { allowStatus = allowObject.getAsString(); if (Boolean.parseBoolean(allowStatus)) { allowStatus = "APPROVED"; String sessionID = DatabaseUtils.getMePinSessionID(respTransactionId); DatabaseUtils.updateStatus(sessionID, allowStatus); } } } catch (IOException e) { log.error("Error while MePIN Status request" + e); } catch (SQLException e) { log.error("Error in connecting to DB" + e); } return allowStatus; }
From source file:com.logger.TrackServlet.java
private String getJsonData(String ip) { String result = ""; try {// w ww . ja v a2 s .co m URL url = new URL("https://stat.ripe.net/data/whois/data.json?resource=" + ip); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.connect(); int status = connection.getResponseCode(); if (status == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { result += line; } } } catch (MalformedURLException ex) { Logger.getLogger(TrackServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(TrackServlet.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:no.digipost.android.api.ApiAccess.java
public static void uploadFile(Context context, String uri, File file) throws DigipostClientException { try {/*from w ww. j a v a 2 s . co m*/ try { FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(ApiConstants.ENCODING)); multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()), ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING))); multipartEntity.addPart("file", filebody); multipartEntity.addPart("token", new StringBody(TokenStore.getAccess())); URL url = new URL(uri); HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection(); httpsClient.setRequestMethod("POST"); httpsClient.setDoOutput(true); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength()); } else { httpsClient.setChunkedStreamingMode(0); } httpsClient.setRequestProperty("Connection", "Keep-Alive"); httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + ""); httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION, ApiConstants.BEARER + TokenStore.getAccess()); httpsClient.addRequestProperty(multipartEntity.getContentType().getName(), multipartEntity.getContentType().getValue()); try { OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream()); multipartEntity.writeTo(outputStream); outputStream.flush(); NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode()); } finally { httpsClient.disconnect(); } } catch (DigipostInvalidTokenException e) { OAuth.updateAccessTokenWithRefreshToken(context); uploadFile(context, uri, file); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, context.getString(R.string.error_your_network)); throw new DigipostClientException(context.getString(R.string.error_your_network)); } }
From source file:com.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java
/** * This method performs a simple HTTP request to the BOSH director and * returns the results//w w w.ja v a2 s. c om * * @param path the path to query * @return a {@link BoshResponse} object with the status code, the headers and the body of the response * @throws BoshClientException if there are problems */ public BoshResponse doSimpleRequest(String path) throws BoshClientException { try { String fixedPath; if (path.startsWith("/")) { fixedPath = path; } else { fixedPath = "/" + path; } HttpsURLConnection httpsURLConnection = setupHttpsUrlConnection(fixedPath); int statusCode = httpsURLConnection.getResponseCode(); String responseBody = getResponseBody(httpsURLConnection); Map<String, List<String>> headers = httpsURLConnection.getHeaderFields(); BoshResponse result = new BoshResponse(statusCode, headers, responseBody); return result; } catch (IOException e) { throw new BoshClientException("Error performing HTTP request (more info in the cause)", e); } }
From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java
/** * Posts the JSON string to the URL. For either the telemetry or the stop * command./*from w w w. j a v a2s. com*/ * * @param baseUrl * @param jsonStr * @return True if successfully posted the data */ private static boolean post(String baseUrl, String jsonStr) { try { // Create the connection URL url = new URL(baseUrl); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); // Set parameters for the connection con.setRequestMethod("POST"); con.setRequestProperty("content-type", "application/json"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); // API now uses basic authentication String authString = login.getValue() + ":" + password.getValue(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); con.setRequestProperty("Authorization", "Basic " + authStringEnc); // Set the timeout so don't wait forever (unless timeout is set to 0) int timeoutMsec = timeout.getValue(); con.setConnectTimeout(timeoutMsec); con.setReadTimeout(timeoutMsec); // Write the json data to the connection DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonStr); wr.flush(); wr.close(); // Get the response int responseCode = con.getResponseCode(); // If wasn't successful then log the response so can debug if (responseCode != 200) { String responseStr = ""; if (responseCode != 500) { // Response code indicates there was a problem so get the // reply in case API returned useful error message InputStream inputStream = con.getErrorStream(); if (inputStream != null) { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); responseStr = response.toString(); } } // Lot that response code indicates there was a problem logger.error( "Bad HTTP response {} when writing data to SFMTA " + "API. Response text=\"{}\" URL={} json=\n{}", responseCode, responseStr, baseUrl, jsonStr); } // Done so disconnect just for the heck of it con.disconnect(); // Return whether was successful return responseCode == 200; } catch (IOException e) { logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(), baseUrl, jsonStr); // Return that was unsuccessful return false; } }
From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java
private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken) throws IOException, HttpResultException { HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection(); nection.setDoInput(true);/* w w w . j a v a 2 s . co m*/ nection.setDoOutput(true); nection.setConnectTimeout(2000); nection.setReadTimeout(1000); nection.setRequestProperty("Content-Type", "application/json"); nection.setRequestProperty("Accept", "application/json"); nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME); if (accessToken != null) { nection.setRequestProperty("Authorization", "token " + accessToken); } OutputStream os = nection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(params.toString()); writer.flush(); writer.close(); os.close(); try { nection.connect(); int code = nection.getResponseCode(); if (code != HttpsURLConnection.HTTP_CREATED && code != HttpsURLConnection.HTTP_OK) { throw new HttpResultException(nection.getResponseCode(), nection.getResponseMessage()); } InputStream in = new BufferedInputStream(nection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); while (true) { String line = reader.readLine(); if (line == null) { break; } response.append(line); } try { return new JSONObject(response.toString()); } catch (JSONException e) { throw new IOException(e); } } finally { nection.disconnect(); } }