List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:org.apache.hadoop.hdfs.web.WebHdfsFileSystem.java
private static Map<?, ?> validateResponse(final HttpOpParam.Op op, final HttpURLConnection conn) throws IOException { final int code = conn.getResponseCode(); if (code != op.getExpectedHttpResponseCode()) { final Map<?, ?> m; try {/*from w w w . jav a 2 s .c om*/ m = jsonParse(conn.getErrorStream()); } catch (IOException e) { throw new IOException( "Unexpected HTTP response: code=" + code + " != " + op.getExpectedHttpResponseCode() + ", " + op.toQueryString() + ", message=" + conn.getResponseMessage(), e); } if (m.get(RemoteException.class.getSimpleName()) == null) { return m; } final RemoteException re = JsonUtil.toRemoteException(m); throw re.unwrapRemoteException(AccessControlException.class, InvalidToken.class, AuthenticationException.class, AuthorizationException.class, FileAlreadyExistsException.class, FileNotFoundException.class, SafeModeException.class, DSQuotaExceededException.class, NSQuotaExceededException.class); } return null; }
From source file:com.shopgun.android.sdk.network.impl.HttpURLNetwork.java
private HttpResponse getHttpResponse(HttpURLConnection connection) throws IOException { ProtocolVersion pv = new ProtocolVersion("HTTP", 1, 1); String rm = connection.getResponseMessage(); HttpResponse response = new BasicHttpResponse(pv, connection.getResponseCode(), rm); 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);/*from w w w . ja v a 2 s . c om*/ } } return response; }
From source file:org.apache.axis2.transport.testkit.http.JavaNetClient.java
public void sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception { URL url = new URL(channel.getEndpointReference().getAddress()); log.debug("Opening connection to " + url + " using " + URLConnection.class.getName()); try {/* w w w .j av a 2 s . co m*/ URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", contentType.toString()); if (contentType.getBaseType().equals("text/xml")) { connection.setRequestProperty("SOAPAction", ""); } OutputStream out = connection.getOutputStream(); out.write(message); out.close(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; log.debug("Response code: " + httpConnection.getResponseCode()); log.debug("Response message: " + httpConnection.getResponseMessage()); int i = 0; String headerValue; while ((headerValue = httpConnection.getHeaderField(i)) != null) { String headerName = httpConnection.getHeaderFieldKey(i); if (headerName != null) { log.debug(headerName + ": " + headerValue); } else { log.debug(headerValue); } i++; } } InputStream in = connection.getInputStream(); IOUtils.copy(in, System.out); in.close(); } catch (IOException ex) { log.debug("Got exception", ex); throw ex; } }
From source file:it.polito.tellmefirst.web.rest.apimanager.RestManager.java
public String getStringFromAPI(String urlStr) { LOG.debug("[getStringFromAPI] - BEGIN"); String result = ""; try {/* w w w .ja v a 2 s . co m*/ URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() != 200) { System.out.println(conn.getResponseCode() + "***********************************"); throw new IOException(conn.getResponseMessage()); } BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); result = sb.toString(); } catch (Exception e) { LOG.error("[getStringFromAPI] - EXCEPTION: ", e); } LOG.debug("[getStringFromAPI] - END"); return result; }
From source file:com.ehsy.solr.util.SimplePostTool.java
private static boolean checkResponseCode(HttpURLConnection urlc) throws IOException { if (urlc.getResponseCode() >= 400) { warn("Solr returned an error #" + urlc.getResponseCode() + " (" + urlc.getResponseMessage() + ") for url: " + urlc.getURL()); Charset charset = StandardCharsets.ISO_8859_1; final String contentType = urlc.getContentType(); // code cloned from ContentStreamBase, but post.jar should be standalone! if (contentType != null) { int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset="); if (idx > 0) { charset = Charset.forName(contentType.substring(idx + "charset=".length()).trim()); }/*from w w w .j a va2 s. c o m*/ } // Print the response returned by Solr try (InputStream errStream = urlc.getErrorStream()) { if (errStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(errStream, charset)); final StringBuilder response = new StringBuilder("Response: "); int ch; while ((ch = br.read()) != -1) { response.append((char) ch); } warn(response.toString().trim()); } } return false; } return true; }
From source file:com.sun.socialsite.pojos.App.java
public static App readFromURL(URL url) throws Exception { HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(false);//from ww w . j a v a 2s. c o m // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.warn("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } con.connect(); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException(con.getResponseMessage()); } InputStream in = con.getInputStream(); return readFromStream(in, url); }
From source file:self.philbrown.droidQuery.XMLResponseHandler.java
public Document handleResponse(HttpURLConnection connection) throws ClientProtocolException, IOException { int statusCode = connection.getResponseCode(); if (statusCode >= 300) { Log.e("droidQuery", "HTTP Response Error " + statusCode + ":" + connection.getResponseMessage()); }/*from w w w . j a v a2s.c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); InputStream is = null; try { is = AjaxUtil.getInputStream(connection); return factory.newDocumentBuilder().parse(is); } catch (IllegalStateException e) { throw e; } catch (SAXException e) { throw new IOException(); } catch (ParserConfigurationException e) { throw new IOException(); } catch (NullPointerException e) { return null; } finally { if (is != null) is.close(); } }
From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java
@Override public TransportFetch httpGetOtherFile(String uri) { TransportFetch result;/*from w w w . ja v a2 s .c om*/ try { final URL url = new URL(serverURL + uri); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); final int responseCode = conn.getResponseCode(); final String responseMessage = conn.getResponseMessage(); InputStream responseIn = conn.getErrorStream(); if (responseIn == null) { responseIn = conn.getInputStream(); } // Read the body to the output if OK otherwise to the error message final byte[] body = IOUtils.toByteArray(responseIn); result = new TransportFetch(responseCode, responseMessage, body); } catch (MalformedURLException ex) { LOG.error("Malformed URL", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } catch (IOException ex) { LOG.error("IO error", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } return result; }
From source file:com.kosbrother.youtubev2.GetSuggestChannelsTask.java
/** * Contacts the user info server to get the profile of the user and extracts the first name * of the user from the profile. In order to authenticate with the user info server the method * first fetches an access token from Google Play services. * @throws IOException if communication with user info server failed. * @throws JSONException if the response from the server could not be parsed. *///from www . j a v a2 s . c om private void fetchNameFromProfileServer() throws IOException, JSONException { // String token = fetchToken(); String token = null; try { token = GoogleAuthUtil.getToken(mActivity, mEmail, mScope); } catch (GooglePlayServicesAvailabilityException playEx) { // GooglePlayServices.apk is either old, disabled, or not present. mActivity.showErrorDialog(playEx.getConnectionStatusCode()); } catch (UserRecoverableAuthException userRecoverableException) { // Unable to authenticate, but the user can fix this. // Forward the user to the appropriate activity. mActivity.startActivityForResult(userRecoverableException.getIntent(), MainActivity.REQUEST_CODE_RECOVER_FROM_AUTH_ERROR); } catch (GoogleAuthException fatalException) { onError("Unrecoverable error " + fatalException.getMessage(), fatalException); } if (token == null) { // error has already been handled in fetchToken() return; } // URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token); // URL url = new URL("https://gdata.youtube.com/feeds/api/users/default/suggestion?type=channel&inline=true&access_token=" // + token + "&key=AIzaSyC6zd4TsN6RR5mJMR_O9srbzXS9OM2R1wg" + "&v=2&max-results=10"+"fields=entry(title,media:thumbnail,yt:channelId)"); URL url = new URL( "https://gdata.youtube.com/feeds/api/users/default/suggestion?type=channel&inline=true&access_token=" + token + "&key=AIzaSyC6zd4TsN6RR5mJMR_O9srbzXS9OM2R1wg" + "&v=2" + "&fields=entry(content(entry(title)))" + "&alt=json"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); int sc = con.getResponseCode(); Log.i(TAG, con.getResponseMessage()); if (sc == 200) { InputStream is = con.getInputStream(); String response = readResponse(is); ArrayList<Channel> channels = getChannels(response); // String name = getFirstName(response); // mActivity.show("Hello " + name + "!"); is.close(); return; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mActivity, token); onError("Server auth error, please try again.", null); Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return; } else { onError("Server returned the following error code: " + sc, null); return; } }
From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java
@Override public TransportFetch httpGetTheFile() { TransportFetch result;//from ww w.j a va2 s . c o m try { final URL url = new URL(serverURL + theFileURI); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); final int responseCode = conn.getResponseCode(); final String responseMessage = conn.getResponseMessage(); InputStream responseIn = conn.getErrorStream(); if (responseIn == null) { responseIn = conn.getInputStream(); } // Read the body to the output if OK otherwise to the error message final byte[] body = IOUtils.toByteArray(responseIn); this.targetResponse = new TargetResponse(responseCode, conn.getHeaderFields(), body); result = new TransportFetch(responseCode, responseMessage, body); } catch (MalformedURLException ex) { LOG.error("Malformed URL", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } catch (IOException ex) { LOG.error("IO error", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } return result; }