List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.kosbrother.youtubefeeder.api.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 w w w . j a v a 2 s. c o m 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(), RecommendChannelsActivity.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:self.philbrown.droidQuery.ScriptResponseHandler.java
public ScriptResponse 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 .ja v a2 s.c om ScriptResponse script = new ScriptResponse(); InputStream stream = AjaxUtil.getInputStream(connection); script.text = Ajax.parseText(stream); //new line characters currently represent a new command. //Although one file can be all one line, it will be executed as a shell script. //for something else, the first line should contain be: #!<shell>\n, where <shell> points //to the shell that should be used. String[] commands = script.text.split("\n"); script.script = new Script(context, commands); try { script.output = script.script.execute(); } catch (Throwable t) { //could not execute script script.output = null; } finally { if (stream != null) { stream.close(); } } return script; }
From source file:com.maltera.technologic.maven.mcforge.detect.CentralHashDetector.java
public void detect(Target target) throws MojoFailureException, MojoExecutionException { try {// w ww. j av a 2 s. co m final URL url = new URL("http://search.maven.org/solrsearch/select" + "?q=1:\"" + target.getHash() + "\"&rows=1&wt=json"); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); if (200 != conn.getResponseCode()) { throw new MojoFailureException("error querying Nexus on Maven Central: " + conn.getResponseCode() + " " + conn.getResponseMessage()); } final JsonNode result = jackson.readTree(conn.getInputStream()); final JsonNode artifact = result.path("response").path("docs").path(0); if (!artifact.isMissingNode()) { target.foundArtifact( new DefaultArtifact(artifact.path("g").textValue(), artifact.path("a").textValue(), artifact.path("p").textValue(), artifact.path("v").textValue()), "central"); } } catch (IOException caught) { throw new MojoFailureException("error searching Maven Central", caught); } }
From source file:it.polito.tellmefirst.apimanager.RestManager.java
public String getStringFromAPI(String urlStr) { LOG.debug("[getStringFromAPI] - BEGIN - url=" + urlStr); String result = ""; try {//from w w w .j av a2 s .c o m LOG.debug("[getStringFromAPI] - http.proxyHost=" + System.getProperty("http.proxyHost")); LOG.debug("[getStringFromAPI] - http.proxyPort=" + System.getProperty("http.proxyPort")); LOG.debug("[getStringFromAPI] - https.proxyHost=" + System.getProperty("https.proxyHost")); LOG.debug("[getStringFromAPI] - https.proxyPort=" + System.getProperty("https.proxyPort")); LOG.debug("[getStringFromAPI] - http.nonProxyHosts=" + System.getProperty("http.nonProxyHosts")); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); //set timeout to 15 seconds conn.setReadTimeout(15000); //set timeout to 15 seconds if (conn.getResponseCode() != 200) { 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 for url=" + urlStr, e); } LOG.debug("[getStringFromAPI] - END"); return result; }
From source file:com.cloudbees.mtslaves.client.RemoteReference.java
protected void verifyResponseStatus(HttpURLConnection con) throws IOException { if (con.getResponseCode() / 100 != 2) { String msg = "Failed to call " + con.getURL() + " : " + con.getResponseCode() + ' ' + con.getResponseMessage(); InputStream es = con.getErrorStream(); String ct = con.getContentType(); if (ct != null) { HttpHeader contentType = HttpHeader.parse(ct); if (contentType.value.equals("application/json")) { // if the error is JSON, parse it if (es != null) { JSONObject error = JSONObject .fromObject(IOUtils.toString(es, contentType.getSubHeader("charset", "UTF-8"))); throw new ServerException(msg, error, con.getResponseCode(), con.getResponseMessage(), con.getURL()); }/*from w ww . j ava 2s. c o m*/ } } if (es != null) msg += "\n" + IOUtils.toString(es); throw new IOException(msg); } }
From source file:io.mindmaps.engine.loader.DistributedLoader.java
/** * Get the response message from an http connection * @param connection to get response message from * @return the response message/*from www .java2 s.c om*/ */ private String getResponseMessage(HttpURLConnection connection) { try { return connection.getResponseMessage(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.exoplatform.utils.image.CookieAwarePicassoDownloader.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.setUseCaches(true);//from w w w . j a v a 2 s . co m int responseCode = connection.getResponseCode(); 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:ezbake.data.graph.rexster.RexsterRestEzSecurityTokenIntegrationTest.java
/** * Tests that the security token has been set by the time the RexsterApplicationGraph is instantiated. * * @throws java.io.IOException if an error occurred while making the HttpRequest using the URL. * @throws org.apache.thrift.TException If an error occurred serializing the token. */// ww w.j a v a 2 s .c o m @Test public void testContextRexster() throws IOException, TException { final int rexsterServerPort = properties.getConfiguration().getInteger("http.server-port", RexsterSettings.DEFAULT_HTTP_PORT); final String rexsterServerHost = properties.getConfiguration().getString("http.server-host", "0.0.0.0"); final String url = String.format("http://%s:%s/graphs/non-existing-graph", rexsterServerHost, rexsterServerPort); final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestProperty(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(TestUtils.createTS_S_B_User())); assertEquals("Not expected result from http request.", "Not Found", connection.getResponseMessage()); }
From source file:net.smartam.leeloo.controller.ResourceController.java
@RequestMapping public ModelAndView authorize(@ModelAttribute("oauthParams") OAuthParams oauthParams, HttpServletRequest req) { try {/*from w ww .j a v a 2 s.c o m*/ String tokenName = OAuth.OAUTH_TOKEN_DRAFT_0; if (Utils.SMART_GALLERY.equals(oauthParams.getApplication())) { tokenName = OAuth.OAUTH_TOKEN; } URL url = new URL(oauthParams.getResourceUrl() + "?" + tokenName + "=" + oauthParams.getAccessToken()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() == 200) { oauthParams.setResource(OAuthUtils.saveStreamAsString(conn.getInputStream())); } else { oauthParams.setErrorMessage( "Could not access resource: " + conn.getResponseCode() + " " + conn.getResponseMessage()); } } catch (IOException e) { oauthParams.setErrorMessage(e.getMessage()); } return new ModelAndView("resource"); }