List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.vn.apksfull.task.AbstractGetNameTask.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 ww . j a v a2 s .c o m private void fetchNameFromProfileServer() throws IOException, JSONException { String token = fetchToken(); 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); HttpURLConnection con = (HttpURLConnection) url.openConnection(); int sc = con.getResponseCode(); if (sc == 200) { InputStream is = con.getInputStream(); GOOGLE_USER_DATA = readResponse(is); //mActivity.show("Hello " + name + "!"); Log.d(TAG, GOOGLE_USER_DATA); 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:org.openintents.openpgp.keyserver.HkpKeyServer.java
private String submitQuery(String request) throws QueryException, HttpError { InetAddress ips[];/*w w w . ja va 2 s . c om*/ try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); }
From source file:com.amazonaws.http.UrlHttpClient.java
@SuppressWarnings("checkstyle:emptyblock") HttpResponse createHttpResponse(final HttpRequest request, final HttpURLConnection connection) throws IOException { // connection.setDoOutput(true); final String statusText = connection.getResponseMessage(); final int statusCode = connection.getResponseCode(); InputStream content = connection.getErrorStream(); if (content == null) { // HEAD method doesn't have a body if (!"HEAD".equals(request.getMethod())) { try { content = connection.getInputStream(); } catch (final IOException ioe) { // getInputStream() can throw an exception when there is no // input stream. }//w w w . j a v a2s .c o m } } final HttpResponse.Builder builder = HttpResponse.builder().statusCode(statusCode).statusText(statusText) .content(content); for (final Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { // skip null field that stores connection status if (header.getKey() == null) { continue; } // No AWS service return a list of header values, so it's safe to // take the first one. builder.header(header.getKey(), header.getValue().get(0)); } return builder.build(); }
From source file:com.github.cambierr.jcollector.sender.OpenTsdbHttp.java
@Override public void send(ConcurrentLinkedQueue<Metric> _metrics) throws IOException { JSONArray entries = toJson(_metrics); if (entries.length() == 0) { return;//from w ww . j a v a 2 s . co m } HttpURLConnection conn = (HttpURLConnection) host.openConnection(); if (auth != null) { conn.setRequestProperty("Authorization", auth.getAuth()); } conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream body = conn.getOutputStream(); body.write(entries.toString().getBytes()); body.flush(); if (conn.getResponseCode() >= 400) { BufferedReader responseBody = new BufferedReader(new InputStreamReader((conn.getErrorStream()))); String output; StringBuilder sb = new StringBuilder("Could not push data to OpenTSDB through ") .append(getClass().getSimpleName()).append("\n"); while ((output = responseBody.readLine()) != null) { sb.append(output).append("\n"); } Worker.logger.log(Level.WARNING, sb.toString()); throw new IOException(conn.getResponseMessage() + " (" + conn.getResponseCode() + ")"); } }
From source file:eu.codeplumbers.cosi.api.tasks.UnregisterDeviceTask.java
@Override protected String doInBackground(Void... voids) { URL urlO = null;/*w w w .j a v a 2 s . com*/ try { urlO = new URL(url + Device.registeredDevice().getLogin()); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(false); conn.setDoInput(true); conn.setRequestMethod("DELETE"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); if (result == "") { Device.registeredDevice().delete(); new Delete().from(Call.class).execute(); new Delete().from(Note.class).execute(); new Delete().from(Sms.class).execute(); new Delete().from(Place.class).execute(); new Delete().from(File.class).execute(); errorMessage = ""; } else { errorMessage = result; } in.close(); conn.disconnect(); } catch (MalformedURLException e) { errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); } return errorMessage; }
From source file:com.comcast.cmb.test.tools.CNSTestingUtils.java
public static String sendHttpMessage(String endpoint, String message) throws Exception { if ((message == null) || (endpoint == null)) { throw new Exception("Message and Endpoint must both be set"); }/* w w w. j a v a 2 s . com*/ String newPostBody = message; byte newPostBodyBytes[] = newPostBody.getBytes(); URL url = new URL(endpoint); logger.info(">> " + url.toString()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); // POST no matter what con.setDoOutput(true); con.setDoInput(true); con.setFollowRedirects(false); con.setUseCaches(true); logger.info(">> " + "GET"); //con.setRequestProperty("content-length", newPostBody.length() + ""); con.setRequestProperty("host", url.getHost()); con.connect(); logger.info(">> " + newPostBody); int statusCode = con.getResponseCode(); BufferedInputStream responseStream; logger.info("StatusCode:" + statusCode); if (statusCode != 200 && statusCode != 201) { responseStream = new BufferedInputStream(con.getErrorStream()); } else { responseStream = new BufferedInputStream(con.getInputStream()); } int b; String response = ""; while ((b = responseStream.read()) != -1) { response += (char) b; } logger.info("response:" + response); return response; }
From source file:es.tor.push.android.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * // w w w . j a v a 2 s .c o m * @return {@literal true} if the message was sent successfully, * {@literal false} if it failed but could be retried. * * @throws IllegalArgumentException * if registrationIds is {@literal null} or empty. * @throws InvalidRequestException * if GCM didn't returned a 200 status. * @throws IOException * if message could not be sent or received. */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<String, Object> jsonRequest = new HashMap<String, Object>(); jsonRequest.put(PARAM_TIME_TO_LIVE, message.getTimeToLive()); jsonRequest.put(PARAM_COLLAPSE_KEY, message.getCollapseKey()); jsonRequest.put(PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } ObjectMapper mapper = new ObjectMapper(); String requestBody = mapper.writeValueAsString(jsonRequest); // JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); int status = conn.getResponseCode(); String responseBody; if (status != 200) { responseBody = getString(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); throw new InvalidRequestException(status, responseBody); } responseBody = getString(conn.getInputStream()); logger.finest("JSON response: " + responseBody); Map<String, Object> jsonResponse = mapper.readValue(responseBody, new TypeReference<Map<String, Object>>() { }); /*Map<String, Object> jsonResponse = gson.fromJson(requestBody, new TypeToken<Map<String, Object>>() { }.getType());*/ int success = (Integer) jsonResponse.get(JSON_SUCCESS); int failure = (Integer) jsonResponse.get(JSON_FAILURE); int canonicalIds = (Integer) jsonResponse.get(JSON_CANONICAL_IDS); long multicastId = (Long) jsonResponse.get(JSON_MULTICAST_ID); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder().messageId(messageId).canonicalRegistrationId(canonicalRegId) .errorCode(error).build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; }
From source file:org.wso2.msf4j.client.test.ClientTest.java
@Test public void testClient() throws Exception { HttpURLConnection urlConn = request("/report/invoice/I001", HttpMethod.GET, false); InputStream inputStream = urlConn.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream);/* ww w .j a v a2 s .c o m*/ urlConn.disconnect(); Assert.assertEquals(response, "{\"id\":\"I001\",\"customer\":{\"id\":\"C001\",\"firstName\":\"WSO2\",\"lastName\":" + "\"Inc\",\"address\":\"Colombo\"},\"amount\":250.15}"); urlConn = request("/report/invoice/I002", HttpMethod.GET, false); int responseCode = urlConn.getResponseCode(); Assert.assertEquals(responseCode, 404); inputStream = urlConn.getErrorStream(); response = StreamUtil.asString(inputStream); Gson gson = new Gson(); InvoiceNotFoundResponseMapper invoiceNotFoundResponseMapper = gson.fromJson(response, InvoiceNotFoundResponseMapper.class); IOUtils.closeQuietly(inputStream); Assert.assertEquals(invoiceNotFoundResponseMapper.getExceptionKey(), "30002"); Assert.assertEquals(invoiceNotFoundResponseMapper.getExceptionClass(), InvoiceNotFoundRestServiceException.class); urlConn.disconnect(); }
From source file:com.cloudant.http.internal.interceptors.CookieInterceptor.java
private boolean requestCookie(HttpConnectionInterceptorContext context) { try {/*w w w . ja v a 2 s . c om*/ HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded"); conn.setRequestBody(sessionRequestBody); //when we request the session we need all interceptors except this one conn.requestInterceptors.addAll(context.connection.requestInterceptors); conn.requestInterceptors.remove(this); conn.responseInterceptors.addAll(context.connection.responseInterceptors); conn.responseInterceptors.remove(this); HttpURLConnection connection = conn.execute().getConnection(); int responseCode = connection.getResponseCode(); if (responseCode / 100 == 2) { if (sessionHasStarted(connection.getInputStream())) { return storeCookiesFromResponse(connection); } else { return false; } } else { InputStream errorStream = connection.getErrorStream(); try { if (errorStream != null) { // Consume the error stream to avoid leaking connections String error = IOUtils.toString(errorStream, "UTF-8"); // Log the error stream content logger.fine(error); } } finally { IOUtils.closeQuietly(errorStream); } if (responseCode == 401) { logger.severe("Credentials are incorrect, cookie authentication will not be" + " attempted again by this interceptor object"); } else { // catch any other response code logger.log(Level.SEVERE, "Failed to get cookie from server, response code {0}, " + "cookie authentication will not be attempted again", responseCode); } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read cookie response", e); } return false; }
From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java
/** * /*from w w w . j a v a 2 s.co m*/ * also @see com.compositesw.ps.deploytool.dao.RegressionPubTestDAO#executeWs(com.compositesw.ps.deploytool.dao.RegressionPubTestDAO.Item, String, String) */ public static int executeWs(RegressionItem item, String outputFile, CompositeServer cisServerConfig, RegressionTestType regressionConfig, String delimiter, String printOutputType) throws CompositeException { // Set the command and action name String command = "executeWs"; String actionName = "REGRESSION_TEST"; // Check the input parameter values: if (cisServerConfig == null || regressionConfig == null) { throw new CompositeException( "XML Configuration objects are not initialized when trying to run Regression test."); } URLConnection urlConn = null; BufferedReader rd = null; OutputStreamWriter wr = null; int rows = 0; String host = cisServerConfig.getHostname(); int wsPort = cisServerConfig.getPort(); // port in servers.xml defines WS port boolean useHttps = cisServerConfig.isUseHttps(); // Execute the webservice try { // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { boolean encrypt = item.encrypt; // Override the encrypt flag when useHttps is set from an overall PDTool over SSL (https) setting. if (useHttps && !encrypt) { encrypt = true; RegressionManagerUtils.printOutputStr(printOutputType, "summary", "The regression input file encrypt=false has been overridden by useHttps=true for path=" + item.path, ""); } String urlString = "http://" + host + ":" + wsPort + item.path; if (encrypt) { urlString = "https://" + host + ":" + (wsPort + 2) + item.path; } RegressionManagerUtils.printOutputStr(printOutputType, "summary", "urlString=" + urlString, ""); URL url = new URL(urlString); urlConn = url.openConnection(); if (encrypt) { // disable hostname verification ((HttpsURLConnection) urlConn).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }); } // 2014-02-09 (mtinius) - added basic authorization to allow for connections with new users String credentials = cisServerConfig.getUser() + ":" + CommonUtils.decrypt(cisServerConfig.getPassword()); String encoded = Base64EncodeDecode.encodeString(credentials); urlConn.setRequestProperty("Authorization", "Basic " + encoded); urlConn.setRequestProperty("SOAPAction", item.action); urlConn.setRequestProperty("Content-Type", item.contentType); urlConn.setDoOutput(true); wr = new OutputStreamWriter(urlConn.getOutputStream()); wr.write(item.input); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = rd.readLine()) != null) { rows++; buf.append(line); if (outputFile != null) CommonUtils.appendContentToFile(outputFile, line); } line = buf.toString(); RegressionManagerUtils.printOutputStr(printOutputType, "results", line, ""); if (line.indexOf("<fault") >= 0 || line.indexOf(":fault") >= 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("Fault encountered."); } if (line.trim().length() == 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("No response document."); } urlConn.getInputStream().close(); // urlConn.getOutputStream().flush(); wr.close(); rd.close(); RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeWs()", ""); } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } return rows; } catch (IOException e) { try { HttpURLConnection httpConn = (HttpURLConnection) urlConn; BufferedReader brd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = brd.readLine()) != null) { buf.append(line + "\n"); } brd.close(); String error = buf.toString(); throw new ApplicationException("executeWs(): " + error, e); } catch (Exception err) { String error = e.getMessage() + "\n" + "DETAILED_MESSAGE=[" + err.getMessage() + "]"; //debug: System.out.println("*************** ERROR ENCOUNTERED IN executeWs THREAD FOR TYPE:webservice *****************"); throw new ApplicationException("executeWs(): " + error, err); } } finally { try { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } } catch (Exception e) { rd = null; wr = null; throw new CompositeException( "executeWs(): unable to close BufferedReader (rd) and OutputStreamWriter (wr): " + e.getMessage()); } } }