List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private JSONObject queryForJSONResponse(URL url) throws ProtocolException, IOException { JSONObject response = null;/*from w w w .ja v a 2 s. c o m*/ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == 200) { response = new JSONObject(StringUtils.inputStreamToString(connection.getInputStream())); } else { LogHandler.log(this, LogLevel.WARN, "Error in opening: " + url + ", " + connection.getResponseCode() + " " + connection.getResponseMessage()); } return response; }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
private void deleteNamespace(String location) throws Exception { // System.out.println("Delete namespace at " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("DELETE"); conn.setDoOutput(true);/* ww w . j a va2 s . co m*/ conn.connect(); int responseCode = conn.getResponseCode(); // HTTP 200 or 204 if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } }
From source file:it.geosolutions.httpproxy.HttpProxyTest.java
@Test public void testDoGet() throws Exception { // //////////////////////////// // Test with a correct request // //////////////////////////// URL url = new URL("http://localhost:8080/http_proxy/proxy/?" + "url=http%3A%2F%2Fdemo1.geo-solutions.it%2Fgeoserver%2Fwms%3F" + "SERVICE%3DWMS%26REQUEST%3DGetCapabilities%26version=1.1.1"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String response = IOUtils.toString(con.getInputStream()); assertNotNull(response);/*w w w . j a v a2s . c o m*/ assertTrue( response.indexOf("<!DOCTYPE WMT_MS_Capabilities SYSTEM \"http://demo1.geo-solutions.it:80/geoserver" + "/schemas/wms/1.1.1/WMS_MS_Capabilities.dtd\">") != -1); assertTrue(con.getRequestMethod().equals("GET")); assertTrue(con.getResponseCode() == 200); con.disconnect(); // //////////////////////////// // Test with a fake hostname // //////////////////////////// url = new URL( "http://localhost:8080/http_proxy/proxy/?" + "url=http%3A%2F%2FfakeServer%2Fgeoserver%2Fwms%3F" + "SERVICE%3DWMS%26REQUEST%3DGetCapabilities%26version=1.1.1"); con = (HttpURLConnection) url.openConnection(); String message = con.getResponseMessage(); assertNotNull(message); assertEquals(message, "Host Name fakeServer is not among the ones allowed for this proxy"); assertTrue(con.getRequestMethod().equals("GET")); assertTrue(con.getResponseCode() == 403); con.disconnect(); // /////////////////////////////// // Test with a fake request type // /////////////////////////////// url = new URL("http://localhost:8080/http_proxy/proxy/?" + "url=http%3A%2F%2Fdemo1.geo-solutions.it%2Fgeoserver%2Fwms%3F" + "SERVICE%3DWMS%26REQUEST%3DGetCap%26version=1.1.1"); con = (HttpURLConnection) url.openConnection(); message = con.getResponseMessage(); assertNotNull(message); assertEquals(message, "Request Type is not among the ones allowed for this proxy"); assertTrue(con.getRequestMethod().equals("GET")); assertTrue(con.getResponseCode() == 403); con.disconnect(); }
From source file:easyshop.downloadhelper.HttpPageGetter.java
public HttpPage getURLOnly(WebLink url) { log.debug("getURL(" + url + ")"); if (url.getUrlStr() == null) { ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new HttpPage(null, null, conRes, null); }//from ww w .j a v a2 s .c o m URL requestedURL = null; URL referer = null; try { requestedURL = new URL(url.getUrlStr()); log.debug("Creating HTTP connection to " + requestedURL); HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection(); if (referer != null) { log.debug("Setting Referer header to " + referer); conn.setRequestProperty("Referer", referer.toExternalForm()); } if (userAgent != null) { log.debug("Setting User-Agent to " + userAgent); conn.setRequestProperty("User-Agent", userAgent); } conn.setUseCaches(false); log.debug("Opening URL"); long startTime = System.currentTimeMillis(); conn.connect(); String resp = conn.getResponseMessage(); log.debug("Remote server response: " + resp); int code = conn.getResponseCode(); if (code != 200) { log.error("Could not get connection for code=" + code); System.err.println("Could not get connection for code=" + code); } ConnResponse conRes = new ConnResponse(conn.getContentType(), null, 0, 0, code); conn.disconnect(); return new HttpPage(requestedURL.toExternalForm(), null, conRes, conRes.getCharSet()); } catch (IOException ioe) { log.warn("Caught IO Exception: " + ioe.getMessage(), ioe); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } catch (Exception e) { log.warn("Caught Exception: " + e.getMessage(), e); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } }
From source file:com.baasbox.android.HttpUrlConnectionClient.java
@Override public HttpResponse execute(HttpRequest request) throws BaasException { try {/* www . ja v a 2 s . c o m*/ HttpURLConnection connection = openConnection(request.url); for (String name : request.headers.keySet()) { connection.addRequestProperty(name, request.headers.get(name)); } setupConnectionForRequest(connection, request); connection.connect(); int responseCode = -1; try { responseCode = connection.getResponseCode(); } catch (IOException e) { responseCode = connection.getResponseCode(); } Logger.info("Connection response received"); if (responseCode == -1) { throw new IOException("Connection failed"); } StatusLine line = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), responseCode, connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(line); response.setEntity(asEntity(connection)); for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; } catch (IOException e) { throw new BaasIOException(e); } }
From source file:com.github.genium_framework.appium.support.server.AppiumServer.java
/** * Checks whether an Appium server instance is running or not by sending an * HTTP request to the server asking for status. * * @param silentMode Whether or not to log info messages. True will activate * silent mode and no messages would be logged. * @return True if an Appium server is already running, false otherwise. *///from w w w . j a va2 s . c o m private boolean isServerRunning(boolean silentMode) { HttpURLConnection openConnection; try { if (silentMode == false) { LOGGER.log(Level.INFO, "Checking to see if a server instance is running or not ..."); } String serverIPAddress = _serverArguments.get(AppiumCommonArgs.IP_ADDRESS).toString(); String serverPortNumber = _serverArguments.get(AppiumCommonArgs.PORT_NUMBER).toString(); URL url = new URL("http://" + serverIPAddress + ":" + serverPortNumber + "/wd/hub/status"); openConnection = (HttpURLConnection) url.openConnection(); openConnection.connect(); /** * If the server is up an running it will return a response massage * that says "OK" */ return openConnection.getResponseMessage().equalsIgnoreCase("ok"); } catch (java.net.ConnectException ex) { return false; } catch (Exception ex) { LOGGER.log(Level.SEVERE, "An exception was thrown.", ex); } return false; }
From source file:org.apache.cocoon.generation.LinkStatusGenerator.java
/** * Generate xml attributes of a url, calculate url for retrieving links * * @param url to process//w ww . j a v a 2 s. com * @param referrer of the url * @return String url for retrieving links, or null if url is an excluded-url, * and not an included-url. */ protected String processURL(URL url, String referrer) throws SAXException { if (getLogger().isDebugEnabled()) { getLogger().debug("getLinks URL " + url); } String result = null; // don't try to investigate a url which has been crawled already if (crawled.contains(url.toString())) { return null; } // mark it as crawled crawled.add(url.toString()); attributes.clear(); attributes.addAttribute("", HREF_ATTR_NAME, HREF_ATTR_NAME, "CDATA", url.toString()); attributes.addAttribute("", REFERRER_ATTR_NAME, REFERRER_ATTR_NAME, "CDATA", referrer); // Output url, referrer, content-type, status, message for traversable url's HttpURLConnection h = null; try { URLConnection links_url_connection = url.openConnection(); h = (HttpURLConnection) links_url_connection; String content_type = links_url_connection.getContentType(); attributes.addAttribute("", CONTENT_ATTR_NAME, CONTENT_ATTR_NAME, "CDATA", content_type); attributes.addAttribute("", MESSAGE_ATTR_NAME, MESSAGE_ATTR_NAME, "CDATA", h.getResponseMessage()); attributes.addAttribute("", STATUS_ATTR_NAME, STATUS_ATTR_NAME, "CDATA", String.valueOf(h.getResponseCode())); } catch (IOException ioe) { attributes.addAttribute("", MESSAGE_ATTR_NAME, MESSAGE_ATTR_NAME, "CDATA", ioe.getMessage()); } finally { if (h != null) { h.disconnect(); } } // don't try to get links of a url which is excluded from crawling // try to get links of a url which is included for crawling if (!isExcludedURL(url.toString()) && isIncludedURL(url.toString())) { // add prefix and query to get data from the linkserializer. result = url.toExternalForm() + ((url.toExternalForm().indexOf("?") == -1) ? "?" : "&") + linkViewQuery; } super.contentHandler.startElement(URI, LINK_NODE_NAME, PREFIX + ':' + LINK_NODE_NAME, attributes); super.contentHandler.endElement(URI, LINK_NODE_NAME, PREFIX + ':' + LINK_NODE_NAME); return result; }
From source file:org.runnerup.export.GarminSynchronizer.java
private Status checkLogin() throws MalformedURLException, IOException, JSONException { HttpURLConnection conn = (HttpURLConnection) new URL(CHECK_URL).openConnection(); addCookies(conn);//w ww . j a va 2 s . c om { conn.connect(); getCookies(conn); String str = SyncHelper.readInputStream(conn.getInputStream()); Log.e(getName(), "checkLogin: str: " + str); JSONObject obj = SyncHelper.parse(str); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); // Returns username(which is actually Displayname from profile) if // logged in if (obj.optString("username", "").length() > 0) { isConnected = true; return Synchronizer.Status.OK; } else { Log.e(getName(), "GarminSynchronizer::connect() missing username, obj: " + obj.toString() + ", code: " + responseCode + ", msg: " + amsg); } Status s = Status.NEED_AUTH; s.authMethod = Synchronizer.AuthMethod.USER_PASS; return s; } }
From source file:org.exoplatform.utils.image.ExoPicassoDownloader.java
@Override public Response load(Uri uri, int networkPolicy) throws IOException { // TODO use networkPolicy as in com.squareup.picasso.UrlConnectionDownloader // https://github.com/square/picasso/blob/picasso-parent-2.5.2/picasso/src/main/java/com/squareup/picasso/UrlConnectionDownloader.java HttpURLConnection connection = connection(uri); connection.setInstanceFollowRedirects(true); connection.setUseCaches(true);/* w w w . j a v a 2s . com*/ int responseCode = connection.getResponseCode(); // Handle HTTP redirections that are not managed by HttpURLConnection // automatically, e.g. HTTP -> HTTPS // TODO consider using OkHttp instead if (responseCode >= 300 && responseCode < 400) { String location = connection.getHeaderField("Location"); connection.disconnect(); connection = connection(Uri.parse(location)); connection.setInstanceFollowRedirects(true); connection.setUseCaches(true); responseCode = connection.getResponseCode(); } // Either the original or the new request have failed -> error if (responseCode >= 300) { connection.disconnect(); throw new ResponseException(responseCode + " " + connection.getResponseMessage(), networkPolicy, responseCode); } long contentLength = connection.getHeaderFieldInt("Content-Length", -1); // boolean fromCache = // parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE)); boolean fromCache = false; return new Response(connection.getInputStream(), fromCache, contentLength); }
From source file:com.example.appengine.UrlFetchServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String id = req.getParameter("id"); String text = req.getParameter("text"); if (id == null || text == null || id == "" || text == "") { req.setAttribute("error", "invalid input"); req.getRequestDispatcher("/main.jsp").forward(req, resp); return;/* w ww .j a v a 2 s. com*/ } JSONObject jsonObj = new JSONObject().put("userId", 33).put("id", id).put("title", text).put("body", text); // [START complex] URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8")); writer.close(); int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) { req.setAttribute("error", ""); StringBuffer response = new StringBuffer(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); req.setAttribute("response", response.toString()); } else { req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage()); } // [END complex] req.getRequestDispatcher("/main.jsp").forward(req, resp); }