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.impetus.ankush.common.utils.AnkushRestClient.java
/** * Method sendNodeInfo./*from w w w .j a va 2 s . c om*/ * * @param urlPath * String * @param input * String * @return String * @throws IOException */ public HttpResult sendRequest(String urlPath, String input, String method, String accept, String contentType) { HttpURLConnection conn = null; String output = ""; OutputStream os = null; // Http Response object. HttpResult result = new HttpResult(); boolean status = true; try { URL url = new URL(urlPath); logger.info("Executing request : " + urlPath); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method); conn.setRequestProperty("Accept", accept); conn.setRequestProperty("Content-type", contentType); if (input != null && !input.isEmpty()) { os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); } String buffer = ""; BufferedReader br; if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { status = false; String error = ""; // get ErrorStream br = new BufferedReader(new InputStreamReader((conn.getErrorStream()))); while ((buffer = br.readLine()) != null) { error += buffer; } result.setError(error); } br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); while ((buffer = br.readLine()) != null) { output += buffer; } } catch (Exception e) { logger.debug(e.getMessage()); logger.error("Exception in executing request : " + urlPath, e); result.setError(e.getLocalizedMessage()); status = false; } finally { if (conn != null) { conn.disconnect(); } if (os != null) { IOUtils.closeQuietly(os); } } result.setStatus(status); result.setOutput(output); return result; }
From source file:net.namecoin.NameCoinI2PResolver.HttpSession.java
public String executePost(String postdata) throws HttpSessionException { URL url;//from w w w . ja v a 2s. c om HttpURLConnection connection = null; try { //Create connection url = new URL(this.uri); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", POST_CONTENT_TYPE); connection.setRequestProperty("User-Agent", "java"); if (!this.user.isEmpty() && !this.password.isEmpty()) { String authString = this.user + ":" + this.password; String authStringEnc = Base64.encodeBytes(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(postdata); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new HttpSessionException("Server returned: " + connection.getResponseMessage()); } return response.toString(); } catch (Exception e) { throw new HttpSessionException(e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:rogerthat.topdesk.bizz.Util.java
public static String topdeskAPIGet(String apiKey, String path) throws IOException, ParseException { final Settings settings = Settings.get(); URL url = new URL(settings.get("TOPDESK_API_URL") + path); HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(30)); request.addHeader(new HTTPHeader("Authorization", "TOKEN id=\"" + apiKey + "\"")); request.addHeader(new HTTPHeader("Content-type", "application/json")); request.addHeader(new HTTPHeader("Accept", "application/json")); URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService(); HTTPResponse response = urlFetch.fetch(request); String content = getContent(response); int responseCode = response.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new TopdeskApiException( "GET to " + path + " failed with response code " + responseCode + "\nContent:" + content); }/*from w w w . ja v a 2 s .c o m*/ return content; }
From source file:eu.liveandgov.ar.utilities.OS_Utils.java
/** * Check if URL exists /* w ww . j a v a2s . c o m*/ * * @param urlSTR * @return */ public static boolean exists(String URLName) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { return false; } }
From source file:com.onesignal.OneSignalRestClient.java
private static void makeRequest(String url, String method, JSONObject jsonBody, ResponseHandler responseHandler) { HttpURLConnection con = null; int httpResponse = -1; String json = null;//from w w w . j a v a 2 s . c o m try { con = (HttpURLConnection) new URL(BASE_URL + url).openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); if (jsonBody != null) con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestMethod(method); if (jsonBody != null) { String strJsonBody = jsonBody.toString(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody); byte[] sendBytes = strJsonBody.getBytes("UTF-8"); con.setFixedLengthStreamingMode(sendBytes.length); OutputStream outputStream = con.getOutputStream(); outputStream.write(sendBytes); } httpResponse = con.getResponseCode(); InputStream inputStream; Scanner scanner; if (httpResponse == HttpURLConnection.HTTP_OK) { inputStream = con.getInputStream(); scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json); if (responseHandler != null) responseHandler.onSuccess(json); } else { inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); if (inputStream != null) { scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json); } else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " HTTP Code: " + httpResponse + " No response body!"); if (responseHandler != null) responseHandler.onFailure(httpResponse, json, null); } } catch (Throwable t) { if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException) OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "Could not send last request, device is offline. Throwable: " + t.getClass().getName()); else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t); if (responseHandler != null) responseHandler.onFailure(httpResponse, null, t); } finally { if (con != null) con.disconnect(); } }
From source file:mdretrieval.FileFetcher.java
public static String[] loadStringFromURL(String destinationURL, boolean acceptRDF) throws IOException { String[] ret = new String[2]; HttpURLConnection urlConnection = null; InputStream inputStream = null; String dest = destinationURL; URL url = new URL(dest); Proxy proxy = null;/*from w w w . ja v a 2 s . c om*/ if (ServerConstants.isProxyEnabled) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ServerConstants.hostname, ServerConstants.port)); urlConnection = (HttpURLConnection) url.openConnection(proxy); } else { urlConnection = (HttpURLConnection) url.openConnection(); } boolean redirect = false; int status = urlConnection.getResponseCode(); if (Master.DEBUG_LEVEL >= Master.LOW) System.out.println("RESPONSE-CODE--> " + status); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { String newUrl = urlConnection.getHeaderField("Location"); dest = newUrl; urlConnection.disconnect(); if (Master.DEBUG_LEVEL > Master.LOW) System.out.println("REDIRECT--> " + newUrl); urlConnection = openMaybeProxyConnection(proxy, newUrl); } try { urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Accept", HTTP_RDFXML_PROP); urlConnection.setDoInput(true); //urlConnection.setDoOutput(true); inputStream = urlConnection.getInputStream(); ret[1] = urlConnection.getHeaderField("Content-Type"); } catch (IllegalStateException e) { if (Master.DEBUG_LEVEL >= Master.LOW) System.out.println(" DEBUG: IllegalStateException"); urlConnection.disconnect(); HttpURLConnection conn2 = openMaybeProxyConnection(proxy, dest); conn2.setRequestMethod("GET"); conn2.setRequestProperty("Accept", HTTP_RDFXML_PROP); conn2.setDoInput(true); inputStream = conn2.getInputStream(); ret[1] = conn2.getHeaderField("Content-Type"); } try { ret[0] = IOUtils.toString(inputStream); if (Master.DEBUG_LEVEL > Master.LOW) { System.out.println(" Content-type: " + urlConnection.getHeaderField("Content-Type")); } } finally { IOUtils.closeQuietly(inputStream); urlConnection.disconnect(); } if (Master.DEBUG_LEVEL > Master.LOW) System.out.println("Done reading " + destinationURL); return ret; }
From source file:i5.las2peer.services.todolist.Todolist.java
/** * //from w ww . j a v a 2 s. c om * getData * * * @return HttpResponse * */ @GET @Path("/data") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "responseGetData") }) @ApiOperation(value = "getData", notes = "") public HttpResponse getData() { JSONObject dataJson = new JSONObject(); Connection conn = null; try { conn = dbm.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM gamificationCAE.todolist ORDER BY id ASC"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { dataJson.put(rs.getInt("id"), rs.getString("name")); } if (!dataJson.isEmpty()) { return new HttpResponse(dataJson.toJSONString(), HttpURLConnection.HTTP_OK); } return new HttpResponse("No data Found", HttpURLConnection.HTTP_OK); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return new HttpResponse("Database connection error", HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java
/** * Post data/*from w w w . ja va 2s .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; try { writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); } finally { 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:i5.las2peer.services.videoListService.VideoListService.java
/** * //from w ww. j av a 2s . co m * getVideoList * * * @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 = "videoListAsJSONArray"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "noVideosExist") }) @ApiOperation(value = "getVideoList", notes = "") public HttpResponse getVideoList() { 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 array = new JSONArray(); try { // get connection from connection pool conn = dbm.getConnection(); selectquery = "SELECT * FROM videodetails;"; // 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); } array.add(ro); } if (array.isEmpty()) { String er = "No results"; HttpResponse noVideosExist = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND); return noVideosExist; } else { // return HTTP Response on success HttpResponse videoListAsJSONArray = new HttpResponse(array.toJSONString(), HttpURLConnection.HTTP_OK); return videoListAsJSONArray; } } 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:org.cytoscape.app.internal.net.server.CyHttpdImplTest.java
@Test public void testHttpd() throws Exception { final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2608)); final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl(); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/testA$"); }//from w w w . j a v a 2 s.c o m public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testA response ok", "text/html"); } }); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/testB$"); } public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testB response ok", "text/html"); } }); httpd.addBeforeResponse(new CyHttpBeforeResponse() { public CyHttpResponse intercept(CyHttpRequest request) { if (request.getMethod().equals("OPTIONS")) return responseFactory.createHttpResponse(HttpStatus.SC_OK, "options intercepted", "text/html"); else return null; } }); httpd.addAfterResponse(new CyHttpAfterResponse() { public CyHttpResponse intercept(CyHttpRequest request, CyHttpResponse response) { response.getHeaders().put("SomeRandomHeader", "WowInterceptWorks"); return response; } }); assertFalse(httpd.isRunning()); httpd.start(); assertTrue(httpd.isRunning()); final String url = "http://localhost:2608/"; // test if normal response works HttpURLConnection connection = connectToURL(url + "testA", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "testA response ok"); connection = connectToURL(url + "testB", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "testB response ok"); // test if 404 response works connection = connectToURL(url + "testX", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND); // test if before intercept works connection = connectToURL(url + "testA", "OPTIONS"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "options intercepted"); // test if after intercept works connection = connectToURL(url + "testA", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(connection.getHeaderField("SomeRandomHeader"), "WowInterceptWorks"); httpd.stop(); assertFalse(httpd.isRunning()); }