List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java
public static boolean checkHttpsURLStatus(final String url) { boolean https_StatusFlag = false; System.out.println("Entered in checkHttpsURLStatus >>>>>>>>>>>>>>>"); URL httpsurl;//from w w w.ja v a2 s. com try { // Create a context that doesn't check certificates. SSLContext ssl_ctx = SSLContext.getInstance("TLS"); TrustManager[] trust_mgr = get_trust_mgr(); ssl_ctx.init(null, // key manager trust_mgr, // trust manager new SecureRandom()); // random number generator HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory()); System.out.println("Url =========" + url); httpsurl = new URL(url); HttpsURLConnection con = (HttpsURLConnection) httpsurl.openConnection(); con.setHostnameVerifier(DO_NOT_VERIFY); int statusCode = con.getResponseCode(); System.out.println("statusCode =========" + statusCode); if (statusCode == HttpURLConnection.HTTP_OK) { https_StatusFlag = true; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return https_StatusFlag; }
From source file:org.peterbaldwin.vlcremote.sweep.Worker.java
@Override public void run() { // Note: InetAddress#isReachable(int) always returns false for Windows // hosts because applications do not have permission to perform ICMP // echo requests. for (;;) {/*from w w w. j ava 2s . c om*/ byte[] ipAddress = mManager.pollIpAddress(); if (ipAddress == null) { break; } try { InetAddress address = InetAddress.getByAddress(ipAddress); String hostAddress = address.getHostAddress(); URL url = createUrl("http", hostAddress, mPort, mPath); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1000); try { int responseCode = connection.getResponseCode(); String responseMessage = connection.getResponseMessage(); InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? connection.getInputStream() : connection.getErrorStream(); if (inputStream != null) { try { int length = connection.getContentLength(); InputStreamEntity entity = new InputStreamEntity(inputStream, length); entity.setContentType(connection.getContentType()); // Copy the entire response body into memory // before the HTTP connection is closed: String body = EntityUtils.toString(entity); ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1); String hostname = address.getHostName(); StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage); HttpResponse response = new BasicHttpResponse(statusLine); response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort); response.setEntity(new StringEntity(body)); mCallback.onReachable(ipAddress, response); } finally { inputStream.close(); } } else { Log.w(TAG, "InputStream is null"); } } finally { connection.disconnect(); } } catch (IOException e) { mCallback.onUnreachable(ipAddress, e); } } }
From source file:it.baywaylabs.jumpersumo.robot.ServerPolling.java
/** * This method is called when invoke <b>execute()</b>.<br /> * Do not invoke manually. Use: new ServerPolling().execute(url1, url2, url3); * * @param sUrl List of Url that will be download. * @return null if all is going ok.//w ww . java 2 s . co m */ @Override protected String doInBackground(String... sUrl) { InputStream input = null; OutputStream output = null; File folder = new File(Constants.DIR_ROBOT); String baseName = FilenameUtils.getBaseName(sUrl[0]); String extension = FilenameUtils.getExtension(sUrl[0]); Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension); if (!folder.exists()) { folder.mkdir(); } HttpURLConnection connection = null; if (!f.isUrl(sUrl[0])) return "Url malformed!"; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if (!sUrl[0].endsWith(".csv") && connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); } // this will be useful to display download percentage // might be -1: server did not report the length int fileLength = connection.getContentLength(); // download the file input = connection.getInputStream(); output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling with back button if (isCancelled()) { input.close(); return null; } total += count; // publishing the progress.... if (fileLength > 0) // only if total length is known publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } } catch (Exception e) { Log.e(TAG, e.getMessage()); return e.toString(); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return null; }
From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpUtilImpl.java
/** * Post data// w w w . j av a 2 s .c o m * * @param url * @param data * @return boolean * @throws IOException */ @Override public boolean post(final String url, final String data) throws IOException { httpURL = new URL(url); final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection(); conn.setDoOutput(true); initConnection(conn); OutputStreamWriter writer = null; OutputStream outStream = null; try { outStream = conn.getOutputStream(); writer = new OutputStreamWriter(outStream, "UTF-8"); writer.write(data); writer.flush(); } finally { if (outStream != null) { try { outStream.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } if (writer != null) { try { writer.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } } final int status = conn.getResponseCode(); conn.disconnect(); return status == HttpURLConnection.HTTP_OK; }
From source file:com.github.dpsm.android.print.jackson.JacksonResultOperator.java
@Override public Subscriber<? super Response> call(final Subscriber<? super T> subscriber) { return new Subscriber<Response>() { @Override//from w w w . jav a 2 s .c om public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(final Throwable e) { subscriber.onError(e); } @Override public void onNext(final Response response) { switch (response.getStatus()) { case HttpURLConnection.HTTP_OK: InputStreamReader reader = null; try { reader = new InputStreamReader(response.getBody().in()); final ObjectNode rootNode = mMapper.readValue(reader, ObjectNode.class); T result = mConstructor.newInstance(rootNode); subscriber.onNext(result); } catch (Exception e) { subscriber.onError(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Nothing to do here } } } break; default: break; } } }; }
From source file:cn.keke.travelmix.publictransport.JsonProxyRouter.java
public void handle(HttpExchange xchg) throws IOException { try {// ww w . j a v a 2 s . co m StringBuffer response = new StringBuffer(4096); String query = xchg.getRequestURI().getRawQuery(); String callbackMethod = HttpClientHelper.parseQueryMap(query).get("callback"); response.append(callbackMethod).append("("); LOG.info(query); if (StringUtils.isNotEmpty(query)) { RoutingJob job = createRoutingJob(query); if (job != null) { RoutingTask task = null; Header[] headers = convertRequestHeaders(xchg.getRequestHeaders()); List<Future<String>> futures = new ArrayList<Future<String>>(Provider.values().length); while ((task = job.pop()) != null) { task.setHeaders(headers); task.setResponse(response); futures.add(ExecutorUtils.THREAD_POOL.submit(task)); } for (Future<String> future : futures) { if (job.isHandled()) { System.out.println("Finished: " + job); break; } else { future.get(); } } } } response.append(");"); xchg.getResponseHeaders().set("Content-Encoding", "gzip"); xchg.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); GZIPOutputStream os = new GZIPOutputStream(xchg.getResponseBody()); LOG.info(response.toString()); os.write(response.toString().getBytes()); os.finish(); xchg.close(); } catch (Exception e) { LOG.warn("Json Routing Request failed", e); } }
From source file:com.reactivetechnologies.jaxrs.RestServerTest.java
static String sendPost(String url, String content) throws IOException { StringBuilder response = new StringBuilder(); HttpURLConnection con = null; BufferedReader in = null;//from ww w.j ava2s.co m try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("POST"); //add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeUTF(content); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } else { throw new IOException("Response Code: " + responseCode); } return response.toString(); } catch (IOException e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (con != null) { con.disconnect(); } } }
From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java
public String readChangeStatus(@NotNull final String repoOwner, @NotNull final String repoName, @NotNull final String hash) throws IOException { final HttpGet post = new HttpGet(myUrls.getStatusUrl(repoOwner, repoName, hash)); includeAuthentication(post);/*from w w w. j a v a2 s .co m*/ setDefaultHeaders(post); try { logRequest(post, null); final HttpResponse execute = myClient.execute(post); if (execute.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { logFailedResponse(post, null, execute); throw new IOException("Failed to complete request to GitHub. Status: " + execute.getStatusLine()); } return "TBD"; } finally { post.abort(); } }
From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java
/** * /*from w w w . jav a 2 s .c om*/ * getGraphList * * * @return HttpResponse * */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError"), @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "graphListAsJsonArray"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "noGraphExists") }) @ApiOperation(value = "getGraphList", notes = "") public HttpResponse getGraphList() { String result = ""; String columnName = ""; String selectquery = ""; int columnCount = 0; Connection conn = null; PreparedStatement stmnt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; JSONObject ro = null; JSONArray graphList = new JSONArray(); try { // get connection from connection pool conn = dbm.getConnection(); selectquery = "SELECT graphId, description FROM graphs;"; // prepare statement stmnt = conn.prepareStatement(selectquery); // retrieve result set rs = stmnt.executeQuery(); rsmd = (ResultSetMetaData) rs.getMetaData(); columnCount = rsmd.getColumnCount(); // process result set while (rs.next()) { ro = new JSONObject(); for (int i = 1; i <= columnCount; i++) { result = rs.getString(i); columnName = rsmd.getColumnName(i); // setup resulting JSON Object ro.put(columnName, result); } graphList.add(ro); } if (graphList.isEmpty()) { String er = "No results"; HttpResponse noGraphExists = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND); return noGraphExists; } else { // return HTTP Response on success HttpResponse graphListAsJsonArray = new HttpResponse(graphList.toJSONString(), HttpURLConnection.HTTP_OK); return graphListAsJsonArray; } } catch (Exception e) { String er = "Internal error: " + e.getMessage(); HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR); return internalError; } finally { // free resources if (rs != null) { try { rs.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); String er = "Internal error: " + e.getMessage(); HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR); return internalError; } } if (stmnt != null) { try { stmnt.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); String er = "Internal error: " + e.getMessage(); HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR); return internalError; } } if (conn != null) { try { conn.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); String er = "Internal error: " + e.getMessage(); HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR); return internalError; } } } }
From source file:com.theisleoffavalon.mcmanager.mobile.RestClient.java
/** * Sends a JSONRPC request/* ww w . ja v a 2 s. c o m*/ * * @param request * The request to send * @return The response */ private JSONObject sendJSONRPC(JSONObject request) { JSONObject ret = null; try { HttpURLConnection conn = (HttpURLConnection) this.rootUrl.openConnection(); conn.setRequestMethod("POST"); conn.setChunkedStreamingMode(0); conn.setDoInput(true); conn.setDoOutput(true); OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(conn.getOutputStream())); request.writeJSONString(osw); osw.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStreamReader isr = new InputStreamReader(new BufferedInputStream(conn.getInputStream())); ret = (JSONObject) new JSONParser().parse(isr); } else { Log.e("RestClient", String.format("Got %d instead of %d for HTTP Response", conn.getResponseCode(), HttpURLConnection.HTTP_OK)); return null; } } catch (IOException e) { Log.e("RestClient", "Error in sendJSONRPC", e); } catch (ParseException e) { Log.e("RestClient", "Parse return data error", e); } return ret; }