List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:de.tudresden.inf.rn.mobilis.clientservices.socialnetwork.SocialNetworkManager.java
public void loginOAuth2() throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { OAuthConsumer consumer = new DefaultOAuthConsumer(getConsumerKey(), getConsumerSecret()); OAuthProvider provider = new DefaultOAuthProvider(getRequestTokenURL(), getAccessTokenURL(), getAuthorizeURL());/*from w w w. j a v a2 s. c o m*/ Log.v(TAG, "Fetching request token ..."); // we do not support callbacks, thus pass OOB String authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND); Log.v(TAG, "Request token: " + consumer.getToken()); Log.v(TAG, "Token secret: " + consumer.getTokenSecret()); Log.v(TAG, "Now visit:\n" + authUrl + "\n... and grant this app authorization"); Log.v(TAG, "Enter the PIN code and hit ENTER when you're done:"); // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // String pin = br.readLine(); String pin = "abc"; System.out.println("Fetching access token ..."); provider.retrieveAccessToken(consumer, pin); Log.v(TAG, "Access token: " + consumer.getToken()); Log.v(TAG, "Token secret: " + consumer.getTokenSecret()); URL url = new URL("http://twitter.com/statuses/mentions.xml"); HttpURLConnection request = (HttpURLConnection) url.openConnection(); consumer.sign(request); Log.v(TAG, "Sending request..."); request.connect(); Log.v(TAG, "Response: " + request.getResponseCode() + " " + request.getResponseMessage()); }
From source file:com.pushinginertia.commons.net.client.AbstractHttpPostClient.java
/** * Verifies that the response code is {@link java.net.HttpURLConnection#HTTP_OK}. * * @param con instantiated connection/*from ww w. j a va 2s. co m*/ * @throws HttpConnectException if the response code is bad or some communication problem with the remote host occurs */ protected void verifyResponseCode(final HttpURLConnection con) throws HttpConnectException { try { if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { final String msg = "Bad HTTP response code [" + con.getResponseCode() + ": " + con.getResponseMessage() + "] reported by host: " + getHostName(); LOG.error(getClass().getSimpleName(), msg); throw new HttpConnectException(msg); } } catch (HttpConnectException e) { // don't double-wrap the exception! throw e; } catch (Exception e) { final String msg = "An unexpected error occurred while reading the response code from [" + getUrl() + "]: " + e.getMessage(); LOG.error(getClass().getSimpleName(), msg, e); throw new HttpConnectException(msg, e); } }
From source file:jp.primecloud.auto.sdk.Requester.java
protected String request(String endpoint, Map<String, String> parameters) { String queryString = createQueryString(apiPath + endpoint, parameters); String url = this.url + apiPath + endpoint + "?" + queryString; log.trace("[API Request] " + url); HttpURLConnection connection; try {//w w w . j av a 2 s . c o m connection = createConnection(url, options); } catch (Exception e) { throw new RuntimeException(e); } try { int code = connection.getResponseCode(); if (code != 200) { throw new RuntimeException(connection.getResponseMessage()); } String body = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8); log.trace("[API Response] " + body); return body; } catch (IOException e) { throw new RuntimeException(e); } finally { connection.disconnect(); } }
From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java
private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project, boolean setProjectDir) { URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir); if (url == null) { return null; }// w w w . j a va 2 s.c o m HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(50); httpConnection.setReadTimeout(1000); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setRequestProperty("Content-Type", "application/json"); httpConnection.connect(); try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) { final String jsonRequest = new Gson().toJson(request); writer.write(jsonRequest); writer.flush(); writer.close(); } if (httpConnection.getResponseCode() == 200) { if (responseClass == null) { return null; } try (InputStream inputStream = httpConnection.getInputStream()) { String jsonResponse = IOUtils.toString(inputStream, "UTF-8"); R response = new Gson().fromJson(jsonResponse, responseClass); return response; } } else { log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode() + ": " + httpConnection.getResponseMessage()); } } catch (IOException e) { log.warn("Unable to connect to dev server", e); } finally { if (httpConnection != null) { httpConnection.disconnect(); } } return null; }
From source file:ai.grakn.engine.loader.client.LoaderClient.java
/** * Get the response message from an http connection * @param connection to get response message from * @return the response message/* w ww . j a va2 s.co m*/ */ private String getResponseMessage(HttpURLConnection connection) { try { return connection.getResponseMessage(); } catch (IOException e) { LOG.error(ExceptionUtils.getFullStackTrace(e)); } return null; }
From source file:com.eTilbudsavis.etasdk.network.impl.HttpURLNetwork.java
public HttpResponse performNetworking(Request<?> request) throws ClientProtocolException, IOException { URL url = new URL(Utils.requestToUrlAndQueryString(request)); HttpURLConnection connection = openConnection(url, request); setHeaders(request, connection);/*from w ww . j a va2 s.co m*/ setRequestMethod(connection, request); int sc = connection.getResponseCode(); if (sc == -1) { throw new IOException("Connection returned invalid response code."); } ProtocolVersion pv = new ProtocolVersion("HTTP", 1, 1); String rm = connection.getResponseMessage(); BasicHttpResponse response = new BasicHttpResponse(pv, sc, rm); HttpEntity entity = getEntity(connection); response.setEntity(entity); 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:net.sf.okapi.filters.drupal.DrupalConnector.java
public Node getNode(String nodeId) { try {//w w w. ja va2s.com URL url = new URL(host + String.format("rest/node/%s", nodeId)); HttpURLConnection conn = createConnection(url, "GET", false); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { conn.disconnect(); throw new RuntimeException("Error in getNode(): " + conn.getResponseMessage()); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); JSONParser parser = new JSONParser(); JSONObject node = (JSONObject) parser.parse(reader); conn.disconnect(); return new Node(node); } catch (Throwable e) { throw new RuntimeException("Error in getNode(): " + e.getMessage(), e); } }
From source file:eu.krawczyk.shutterstocktask.services.DownloadService.java
@Override protected void onHandleIntent(Intent intent) { String urlPath = intent.getStringExtra(URL); String name = intent.getStringExtra(NAME); File output = new File(Environment.getExternalStorageDirectory(), name); // check if output directory exists if (output.exists()) { output.delete();/*from www . j a v a 2 s . co m*/ } InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { URL url = new URL(urlPath); fileOutputStream = new FileOutputStream(output.getPath()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.e(Constants.General.TAG, "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage()); mResult = EDownloadStatus.FAILED.ordinal(); } else { prepareNotification(); int fileLength = connection.getContentLength(); inputStream = connection.getInputStream(); byte data[] = new byte[BUFFER_SIZE]; long total = 0; int count; while ((count = inputStream.read(data)) != -1 && mIsCancelled == false) { total += count; // publishing the progress.... if (fileLength > 0) { updateNotification((int) (total * 100 / fileLength)); } fileOutputStream.write(data, 0, count); } // finished if (mIsCancelled == true) { mResult = EDownloadStatus.CANCELLED.ordinal(); // Reset mIsCancelled flag mIsCancelled = false; } else { mResult = EDownloadStatus.SUCCESS.ordinal(); } updateNotification(MAX_PROGRESS); } } catch (Exception e) { Log.e(Constants.General.TAG, "Exception while downloading image: " + e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(Constants.General.TAG, "Exception while closing stream: " + e); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { Log.e(Constants.General.TAG, "Exception while closing stream: " + e); } } } publishResults(output.getAbsolutePath(), mResult, 100); }
From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java
/** * Checks if the connection returned one of the provides pass or fail Codes. If not, an * IOException exception is thrown. If it was part of the list, then the actual response code is * returned. returns true if valid response is returned, otherwise false *//*from w w w . ja va 2 s .c o m*/ private boolean validateResponse(HttpURLConnection conn, int passCode, int[] failCodes) throws IOException { responseCode = conn.getResponseCode(); if (responseCode == passCode) { return true; } if ((failCodes == null) || (!ArrayUtils.contains(failCodes, responseCode))) { throw new IOException("Request failed: " + conn.getURL() + " - " + conn.getResponseCode() + " - " + conn.getResponseMessage()); } return false; }
From source file:LNISmokeTest.java
/** * Implement WebDAV PUT http request./*from ww w.j a va 2 s . c o m*/ * * This might be simpler with a real HTTP client library, but * java.net.HttpURLConnection is part of the standard SDK and it * demonstrates the concepts. * * @param lni the lni * @param collHandle the coll handle * @param packager the packager * @param source the source * @param endpoint the endpoint * * @throws RemoteException the remote exception * @throws ProtocolException the protocol exception * @throws IOException Signals that an I/O exception has occurred. * @throws FileNotFoundException the file not found exception */ private static void doPut(LNISoapServlet lni, String collHandle, String packager, String source, String endpoint) throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException { // assemble URL from chopped endpoint-URL and relative URI String collURI = doLookup(lni, collHandle, null); URL url = LNIClientUtils.makeDAVURL(endpoint, collURI, packager); System.err.println("DEBUG: PUT file=" + source + " to URL=" + url.toString()); // connect with PUT method, then copy file over. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true); fixBasicAuth(url, conn); conn.connect(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = conn.getOutputStream(); copyStream(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error("Unable to close input stream", e); } } if (out != null) { try { out.close(); } catch (IOException e) { log.error("Unable to close output stream", e); } } } int status = conn.getResponseCode(); if (status < 200 || status >= 300) { die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage()); } // diagnostics, and get resulting new item's location if avail. System.err.println("DEBUG: sent " + source); System.err.println( "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage()); String loc = conn.getHeaderField("Location"); System.err.println("RESULT: Location=" + ((loc == null) ? "NULL!" : loc)); }