List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());// w ww. j av a2s . c o m map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { VolleyLog.e("======4:" + headerName + ";" + map.get(headerName)); 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); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { 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:com.googlecode.jmxtrans.model.output.LibratoWriter.java
private void writeToLibrato(Server server, Query query, List<Result> results) { HttpURLConnection urlConnection = null; try {//from w w w .jav a2 s. c om 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(server, query, results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, username {}", responseCode, urlConnection.getResponseMessage(), url, proxy, username); } if (logger.isTraceEnabled()) { StringWriter out = new StringWriter(); IOUtils.copy(urlConnection.getInputStream(), out); logger.trace(out.toString()); } } catch (Exception e) { logger.warn("Failure to send result to Librato server '{}' with proxy {}, username {}", url, proxy, username, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IOUtils.copy(err, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(err); } } catch (IOException e) { logger.warn("Exception flushing http connection", e); } } } }
From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java
/** * Notify Desktop that this query has finished, by sending a GET request * to a specific URL. We expect Desktop that view to always return HTTP_OK, * so that we know the notification has been delivered to the right view. * (We don't care whether the notification handling fails or succeeds.) *//*from w ww. ja v a 2 s . com*/ void notifyDone(RunningQueryState state) { if (notifyUrl == null) { return; } QueryHandle handle = state.getQueryHandle(); if (handle == null) { LOG.error("Finished execution of a query without a handle: " + state.toString()); return; } String urlString = notifyUrl + handle.id; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Desktop returns error: " + conn.getResponseMessage()); } LOG.debug("Notified query done at " + url); } catch (IOException ioe) { LOG.error("Error when notifying Desktop at " + urlString, ioe); } }
From source file:com.googlecode.onevre.utils.ServerClassLoader.java
private URL getResourceURL(String name) throws IOException { URL url = cachedFiles.get(name); // If the cached jar is not found, find the class in a remote jar file if (url == null) { return getRemoteResource(name); }/*from ww w . j a v a 2s.c o m*/ // If the cached jar is found, check if it is updated remotely File jar = cachedJars.get(url); if (System.currentTimeMillis() - jar.lastModified() > CACHE_TIMEOUT) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); addSslConnection(connection); connection.setRequestMethod("HEAD"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { long time = connection.getHeaderFieldDate("Last-Modified", System.currentTimeMillis()); // If the remote jar has been updated, // redownload the jar and load it if (jar.lastModified() < time) { downloadJar(url); } else { jar.setLastModified(System.currentTimeMillis()); } } else if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { return getRemoteResource(name); } else { throw new IOException("Connection Error: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } return url; }
From source file:com.nxt.zyl.data.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); // chenbo add gzip support,new user-agent if (request.isShouldGzip()) { map.put(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); }//from w w w. j ava 2s .co m map.put(USER_AGENT, mUserAgent); // end map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } // if (request instanceof MultiPartRequest) { // setConnectionParametersForMultipartRequest(connection, request); // } else { // } 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); } } if (ENCODING_GZIP.equalsIgnoreCase(connection.getContentEncoding())) { response.setEntity(new InflatingEntity(response.getEntity())); } return response; }
From source file:com.oakesville.mythling.util.HttpHelper.java
private byte[] retrieve(Map<String, String> headers) throws IOException { HttpURLConnection conn = null; InputStream is = null;/*from ww w .j a va2 s. c o m*/ try { long startTime = System.currentTimeMillis(); conn = (HttpURLConnection) url.openConnection(); prepareConnection(conn, headers); try { if (postContent != null) writeRequestBytes(conn.getOutputStream()); is = conn.getInputStream(); } catch (IOException ex) { Log.e(TAG, ex.getMessage(), ex); if (ipRetrieval != null) { // try and retrieve the backend IP String ip = retrieveBackendIp(); url = new URL(url.getProtocol(), ip, url.getPort(), url.getFile()); conn = (HttpURLConnection) url.openConnection(); prepareConnection(conn, headers); try { is = conn.getInputStream(); } catch (IOException ex2) { rethrow(ex2, conn.getResponseMessage()); } } else { rethrow(ex, conn.getResponseMessage()); } } return extractResponseBytes(is, startTime); } finally { try { if (is != null) is.close(); } catch (IOException ex) { Log.e(TAG, ex.getMessage(), ex); } } }
From source file:org.runnerup.export.FunBeatSynchronizer.java
@Override public Status connect() { Exception ex = null;//from w w w . j av a 2 s . co m HttpURLConnection conn = null; cookies.clear(); formValues.clear(); Status s = Status.NEED_AUTH; s.authMethod = AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (loginID == null || loginSecretHashed == null) { if (!validateAndCreateSecrets(username, password)) return s; } try { /** * connect to START_URL to get cookies/formValues */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); conn.setInstanceFollowRedirects(false); { int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); getFormValues(conn); Log.i(getName(), "FunBeat.START_URL => code: " + responseCode + "(" + amsg + "), cookies: " + cookies.size() + ", values: " + formValues.size()); } conn.disconnect(); /** * Then login using a post */ FormValues kv = new FormValues(); String viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE"); String eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION"); String userKey = SyncHelper.findName(formValues.keySet(), "Username"); String passKey = SyncHelper.findName(formValues.keySet(), "Password"); String loginKey = SyncHelper.findName(formValues.keySet(), "LoginButton"); kv.put(viewKey, formValues.get(viewKey)); kv.put(eventKey, formValues.get(eventKey)); kv.put(userKey, username); kv.put(passKey, password); kv.put(loginKey, "Logga in"); conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); boolean ok = false; { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { String redirect = conn.getHeaderField("Location"); conn.disconnect(); conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); } else if (responseCode != HttpStatus.SC_OK) { Log.e(getName(), "FunBeatSynchronizer::connect() - got " + responseCode + ", msg: " + amsg); } String html = getFormValues(conn); ok = html.indexOf("Logga ut") > 0; conn.disconnect(); } if (ok) { return Synchronizer.Status.OK; } else { return s; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.openrdf.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);//from ww w . j a va 2s . co 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(); if (responseCode != HttpURLConnection.HTTP_OK && // 200 OK responseCode != HttpURLConnection.HTTP_NO_CONTENT) // 204 NO CONTENT { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
@Test public void testUpdateResponse_HEAD() throws Exception { String query = "INSERT DATA { <foo:foo> <foo:bar> \"foo\". } "; String location = Protocol.getStatementsLocation(TestServer.REPOSITORY_URL); location += "?update=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.connect();//from w w w . java 2 s.com 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); } assertEquals(0, conn.getContentLength()); } 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 upload(SQLiteDatabase db, long mID) { Status s;//from w w w.j a v a 2 s .c om if ((s = connect()) != Status.OK) { return s; } TCX tcx = new TCX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter writer = new StringWriter(); tcx.export(mID, writer); conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); addCookies(conn); Part<StringWritable> part2 = new Part<StringWritable>("data", new StringWritable(writer.toString())); part2.setFilename("RunnerUp.tcx"); part2.setContentType("application/octet-stream"); Part<?> parts[] = { part2 }; SyncHelper.postMulti(conn, parts); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == HttpStatus.SC_OK) { JSONObject reply = SyncHelper .parse(new BufferedReader(new InputStreamReader(conn.getInputStream()))); conn.disconnect(); JSONObject result = reply.getJSONObject("detailedImportResult"); JSONArray successes = result.getJSONArray("successes"); if (successes.length() == 1) { s = Status.OK; s.activityId = mID; String garminID = successes.getJSONObject(0).getString("internalId"); setWorkoutType(tcx.getSport(), garminID); return s; } else { JSONArray failures = result.getJSONArray("failures"); ex = new Exception("Unexpected reply: " + (failures.length() > 0 ? failures.toString() : result.toString())); } } else { ex = new Exception(amsg); } } catch (Exception e) { ex = e; } s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }