List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:export.GarminUploader.java
@Override public void downloadWorkout(File dst, String key) throws Exception { HttpURLConnection conn = null; Exception ex = null;/*from w ww . j a v a2 s . com*/ FileOutputStream out = null; try { conn = (HttpURLConnection) new URL(GET_WORKOUT_URL + key).openConnection(); conn.setRequestMethod("GET"); addCookies(conn); conn.connect(); getCookies(conn); InputStream in = new BufferedInputStream(conn.getInputStream()); out = new FileOutputStream(dst); int cnt = 0; byte buf[] = new byte[1024]; while (in.read(buf) > 0) { cnt += buf.length; out.write(buf); } System.err.println("downloaded workout key: " + key + " " + cnt + " bytes from " + getName()); in.close(); out.close(); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == 200) { return; } ex = new Exception(amsg); } catch (Exception e) { ex = e; } if (conn != null) { try { conn.disconnect(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } ex.printStackTrace(); throw ex; }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
private void putNamespace(String location, String namespace) throws Exception { // System.out.println("Put namespace to " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true);// w w w.j a v a2 s. c o m InputStream dataStream = new ByteArrayInputStream(namespace.getBytes("UTF-8")); try { OutputStream connOut = conn.getOutputStream(); try { IOUtil.transfer(dataStream, connOut); } finally { connOut.close(); } } finally { dataStream.close(); } 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:com.android.volley.toolbox.http.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/* w w w . j a va2s .c o m*/ map.putAll(additionalHeaders); String url = request.getUrl(); if (mUrlRewriter != null) { url = mUrlRewriter.rewriteUrl(url); if (url == null) { throw new IOException("URL blocked by rewriter: " + url); } } URL parsedUrl = new URL(url); System.err.println(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (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; }
From source file:org.jmxtrans.embedded.output.LibratoWriter.java
/** * Send given metrics to the Graphite server. */// ww w. j a v a2 s . c om @Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); List<QueryResult> counters = new ArrayList<QueryResult>(); List<QueryResult> gauges = new ArrayList<QueryResult>(); for (QueryResult result : results) { if (METRIC_TYPE_GAUGE.equals(result.getType())) { gauges.add(result); } else if (METRIC_TYPE_COUNTER.equals(result.getType())) { counters.add(result); } else if (null == result.getType()) { logger.info("Unspecified type for result {}, export it as counter"); counters.add(result); } else { logger.info("Unsupported metric type '{}' for result {}, export it as counter", result.getType(), result); counters.add(result); } } HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(libratoApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); urlConnection.setRequestProperty("User-Agent", httpUserAgent); serialize(counters, gauges, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { exceptionCounter.incrementAndGet(); logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, user {}", responseCode, urlConnection.getResponseMessage(), url, proxy, user); } if (logger.isTraceEnabled()) { IoUtils2.copy(urlConnection.getInputStream(), System.out); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Failure to send result to Librato server '{}' with proxy {}, user {}", url, proxy, user, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } } catch (IOException e) { logger.warn("Exception flushing http connection", e); } } } }
From source file:com.searchtechnologies.aspire.components.heritrixconnector.HeritrixScanner.java
/** * Receive an url, open its connection and inputstream * @param urlParam/* w w w .j a v a2s .c o m*/ * @return InputStream for the contents of the URL * @throws IOException if occurs a problem with the connection or the responseCode is not 200 * @throws AspireException for any MalformedURLException */ protected static InputStream openURLInputStream(String urlParam, boolean successResponse) throws IOException, AspireException { HttpURLConnection urlConn = null; URL url = null; try { url = new URL(StringUtilities.safeUrl(urlParam)); } catch (MalformedURLException e) { throw new AspireException("com.searchtechnologies.aspire.components.heritrixconnector.HeritrixScanner", e, "The URL \"%s\" is reported as being malformed by the java URL parsing utilities.", urlParam); } urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("User-Agent", "Heritrix Crawler connector for Aspire"); //urlConn.setRequestProperty("Accept" ,"text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, *\/*;q=0.1"); if (successResponse && urlConn.getResponseCode() != 200) { throw new IOException( "Response from URL: " + urlParam + " was not successful: " + urlConn.getResponseMessage()); } InputStream is = urlConn.getInputStream(); return is; }
From source file:org.openrdf.http.server.ProtocolTest.java
/** * Checks that a suitable RDF content type is returned when accept header not * explicitly set./*from w w w .j a v a 2 s. c om*/ */ @Test public void testContentTypeForGraphQuery3_GET() throws Exception { String query = "DESCRIBE <foo:bar>"; String location = TestServer.REPOSITORY_URL; location += "?query=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String contentType = conn.getHeaderField("Content-Type"); assertNotNull(contentType); // snip off optional charset declaration int charPos = contentType.indexOf(";"); if (charPos > -1) { contentType = contentType.substring(0, charPos); } RDFFormat format = Rio.getParserFormatForMIMEType(contentType) .orElseThrow(Rio.unsupportedFormat(contentType)); assertNotNull(format); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:org.runnerup.export.GarminSynchronizer.java
@Override public Status listWorkouts(List<Pair<String, String>> list) { Status s;/* w w w.j a va2 s. c om*/ if ((s = connect()) != Status.OK) { return s; } // s = Status.OK HttpURLConnection conn = null; try { Calendar today = Calendar.getInstance(); int month = today.get(Calendar.MONTH); //jan = 0 String str_today = String.format("%1$tY-%1$tm-%1td", today); String workout_url = String.format(CALENDAR_URL, today, month); conn = (HttpURLConnection) new URL(workout_url).openConnection(); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); conn.connect(); getCookies(conn); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = SyncHelper.parse(in); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == HttpStatus.SC_OK) { JSONArray arr = obj.getJSONArray("calendarItems"); for (int i = 0;; i++) { obj = arr.optJSONObject(i); if (obj == null) break; else if (!obj.getString("itemType").equals("workout")) continue; String title = obj.getString("title"); if (obj.optString("date").equals(str_today)) { title = '*' + title; //mark workout scheduled for today } list.add(new Pair<String, String>(getWorkoutIdFromSchedule(obj.getString("id")), title + ".json")); } } else { s = Synchronizer.Status.ERROR; s.ex = new Exception(amsg); } } catch (IOException e) { s = Synchronizer.Status.ERROR; s.ex = e; } catch (JSONException e) { s = Synchronizer.Status.ERROR; s.ex = e; } try { conn = (HttpURLConnection) new URL(LIST_WORKOUTS_URL).openConnection(); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); conn.connect(); getCookies(conn); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = SyncHelper.parse(in); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == HttpStatus.SC_OK) { obj = obj.getJSONObject("com.garmin.connect.workout.dto.BaseUserWorkoutListDto"); JSONArray arr = obj.getJSONArray("baseUserWorkouts"); for (int i = 0;; i++) { obj = arr.optJSONObject(i); if (obj == null) break; list.add(new Pair<String, String>(obj.getString("workoutId"), obj.getString("workoutName") + ".json")); } } else { s = Synchronizer.Status.ERROR; s.ex = new Exception(amsg); } } catch (IOException e) { s = Synchronizer.Status.ERROR; s.ex = e; } catch (JSONException e) { s = Synchronizer.Status.ERROR; s.ex = e; } if (s != Status.OK) { s.ex.printStackTrace(); } return s; }
From source file:edu.pdx.cecs.orcycle.Uploader.java
private boolean uploadOneSegment(long currentNoteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {//from ww w. j a v a 2s . c o m URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); SegmentData segmentData = SegmentData.fetchSegment(mCtx, currentNoteId); JSONObject json = segmentData.getJSON(); String deviceId = userId; DataOutputStream stream = new DataOutputStream(conn.getOutputStream()); stream.writeBytes(makeContentField("ratesegment", json.toString())); stream.writeBytes(makeContentField("version", String.valueOf(kSaveNoteProtocolVersion))); stream.writeBytes(makeContentField("device", deviceId)); stream.writeBytes(contentFieldPrefix); stream.flush(); stream.close(); int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.v(MODULE_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { segmentData.updateSegmentStatus(SegmentData.STATUS_SENT); result = true; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.vuze.android.remote.AndroidUtils.java
private static boolean isURLAlive(String URLName, int conTimeout, int readTimeout) { try {/*from ww w. ja va 2 s .c o m*/ HttpURLConnection.setFollowRedirects(false); URL url = new URL(URLName); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con instanceof HttpsURLConnection) { HttpsURLConnection conHttps = (HttpsURLConnection) con; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); conHttps.setSSLSocketFactory(ctx.getSocketFactory()); } conHttps.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } con.setConnectTimeout(conTimeout); con.setReadTimeout(readTimeout); con.setRequestMethod("HEAD"); con.getResponseCode(); if (DEBUG) { Log.d(TAG, "isLive? conn result=" + con.getResponseCode() + ";" + con.getResponseMessage()); } return true; } catch (Exception e) { if (DEBUG) { Log.e(TAG, "isLive " + URLName, e); } return false; } }
From source file:com.streamsets.datacollector.updatechecker.UpdateChecker.java
@Override public void run() { updateInfo = null;//from w w w . jav a 2s .co m PipelineState ps; try { ps = runner.getState(); } catch (PipelineStoreException e) { LOG.warn(Utils.format("Cannot get pipeline state: '{}'", e.toString()), e); return; } if (ps.getStatus() == PipelineStatus.RUNNING) { if (url != null) { Map uploadInfo = getUploadInfo(); if (uploadInfo != null) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("content-type", APPLICATION_JSON_MIME); ObjectMapperFactory.getOneLine().writeValue(conn.getOutputStream(), uploadInfo); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String responseContentType = conn.getHeaderField("content-type"); if (APPLICATION_JSON_MIME.equals(responseContentType)) { updateInfo = ObjectMapperFactory.get().readValue(conn.getInputStream(), Map.class); } else { LOG.trace("Got invalid content-type '{}' from from update-check server", responseContentType); } } else { LOG.trace("Got '{} : {}' from update-check server", conn.getResponseCode(), conn.getResponseMessage()); } } catch (Exception ex) { LOG.trace("Could not do an update check: {}", ex.toString(), ex); } finally { if (conn != null) { conn.disconnect(); } } } } } }