List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java
@Test public void validFormatWithIncorrectCharset() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim?$format=application/json;charset=utf<8"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;charset=utf-8"); connection.connect();/*www .jav a2 s . c om*/ assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content.contains("The $format option 'application/json;charset=utf<8' is not supported.")); }
From source file:org.jboss.aerogear.android.impl.http.HttpRestProvider.java
private HeaderAndBody getHeaderAndBody(HttpURLConnection urlConnection) throws IOException { int statusCode = urlConnection.getResponseCode(); HeaderAndBody result;/*from ww w. j av a 2s. c o m*/ Map<String, List<String>> headers; byte[] responseData; switch (statusCode) { case HttpStatus.SC_OK: InputStream in = new BufferedInputStream(urlConnection.getInputStream()); responseData = readBytes(in); break; case HttpStatus.SC_NO_CONTENT: responseData = new byte[0]; break; default: InputStream err = new BufferedInputStream(urlConnection.getErrorStream()); byte[] errData = readBytes(err); Map<String, String> errorHeaders = Maps.transformValues(urlConnection.getHeaderFields(), new Function<List<String>, String>() { @Override public String apply(List<String> input) { return TextUtils.join(",", input); } }); throw new HttpException(errData, statusCode, errorHeaders); } headers = urlConnection.getHeaderFields(); result = new HeaderAndBody(responseData, new HashMap<String, Object>(headers.size())); for (Map.Entry<String, List<String>> header : headers.entrySet()) { result.setHeader(header.getKey(), TextUtils.join(",", header.getValue())); } return result; }
From source file:hudson.model.AbstractProjectTest.java
/** * Trying to POST to config.xml by a different job type should fail. *//*from w w w . j av a 2 s .co m*/ @Test public void configDotXmlSubmissionToDifferentType() throws Exception { TestPluginManager tpm = (TestPluginManager) j.jenkins.pluginManager; tpm.installDetachedPlugin("javadoc"); tpm.installDetachedPlugin("junit"); tpm.installDetachedPlugin("display-url-api"); tpm.installDetachedPlugin("mailer"); tpm.installDetachedPlugin("maven-plugin"); j.jenkins.setCrumbIssuer(null); FreeStyleProject p = j.createFreeStyleProject(); HttpURLConnection con = postConfigDotXml(p, "<maven2-moduleset />"); // this should fail with a type mismatch error // the error message should report both what was submitted and what was expected assertEquals(500, con.getResponseCode()); String msg = IOUtils.toString(con.getErrorStream()); System.out.println(msg); assertThat(msg, allOf(containsString(FreeStyleProject.class.getName()), containsString(MavenModuleSet.class.getName()))); // control. this should work con = postConfigDotXml(p, "<project />"); assertEquals(200, con.getResponseCode()); }
From source file:com.paymaya.sdk.android.common.network.AndroidClient.java
@Override public Response call(Request request) { HttpURLConnection conn = initializeConnection(request); try {/* w ww . java 2 s . c o m*/ switch (request.getMethod()) { case GET: conn.setRequestMethod("GET"); break; case POST: conn.setRequestMethod("POST"); break; default: throw new RuntimeException("Invalid method " + request.getMethod()); } if (request.getBody() != null) { conn.setDoOutput(true); write(conn.getOutputStream(), request.getBody()); } int code = conn.getResponseCode(); String message = conn.getResponseMessage(); String response; if (code < 200 || code > 299) { response = read(conn.getErrorStream()); } else { response = read(conn.getInputStream()); } Log.d(TAG, "Status: " + code + " " + message); Log.d(TAG, "Response: " + new JSONObject(response).toString(2)); return new Response(code, response); } catch (IOException | JSONException e) { Log.e(TAG, e.getMessage()); return new Response(-1, ""); } finally { conn.disconnect(); } }
From source file:com.caucho.hessian.client.HessianURLConnection.java
/** * Sends the request/*ww w.j a v a 2 s .co m*/ */ public void sendRequest() throws IOException { if (_conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) _conn; _statusCode = 500; try { _statusCode = httpConn.getResponseCode(); } catch (Exception e) { } parseResponseHeaders(httpConn); InputStream is = null; if (_statusCode != 200) { StringBuffer sb = new StringBuffer(); int ch; try { is = httpConn.getInputStream(); if (is != null) { while ((ch = is.read()) >= 0) sb.append((char) ch); is.close(); } is = httpConn.getErrorStream(); if (is != null) { while ((ch = is.read()) >= 0) sb.append((char) ch); } _statusMessage = sb.toString(); } catch (FileNotFoundException e) { throw new HessianConnectionException("HessianProxy cannot connect to '" + _url, e); } catch (IOException e) { if (is == null) throw new HessianConnectionException(_statusCode + ": " + e, e); else throw new HessianConnectionException(_statusCode + ": " + sb, e); } if (is != null) is.close(); throw new HessianConnectionException(_statusCode + ": " + sb.toString()); } } }
From source file:co.cask.cdap.data2.transaction.TransactionManagerDebuggerMain.java
/** * Prints the error response from the connection * @param connection the connection to read the response from *//* ww w .jav a 2 s . c om*/ private void readUnauthorizedError(HttpURLConnection connection) { System.out.println("401 Unauthorized"); if (accessToken == null) { System.out.println("No access token provided"); return; } Reader reader = null; try { reader = new InputStreamReader(connection.getErrorStream()); String responseError = GSON.fromJson(reader, ErrorMessage.class).getErrorDescription(); if (responseError != null && !responseError.isEmpty()) { System.out.println(responseError); } } catch (Exception e) { System.out.println("Unknown unauthorized error"); } }
From source file:net.bashtech.geobot.BotManager.java
public static String getRemoteContentTwitch(String urlString, int krakenVersion) { String dataIn = ""; try {//from www .j a va2s . c om URL url = new URL(urlString); // System.out.println("DEBUG: Getting data from " + url.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setConnectTimeout(5 * 1000); // conn.setReadTimeout(5 * 1000); if (BotManager.getInstance().krakenClientID.length() > 0) conn.setRequestProperty("Client-ID", BotManager.getInstance().krakenClientID); conn.setRequestProperty("Accept", "application/vnd.twitchtv.v" + krakenVersion + "+json"); try { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) dataIn += inputLine; in.close(); } catch (IOException exerr) { String inputLine; InputStream errorStream = conn.getErrorStream(); if (errorStream != null) { BufferedReader inE = new BufferedReader(new InputStreamReader(errorStream)); while ((inputLine = inE.readLine()) != null) dataIn += inputLine; inE.close(); } } } catch (Exception ex) { ex.printStackTrace(); } return dataIn; }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFolders() { //File.deleteAllFolders(); URL urlO = null;// www . j a v a 2 s .c o m try { urlO = new URL(folderUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // 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(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(folderJson.get("_id").toString()); if (file == null) { file = new File(folderJson, true); } else { file.setName(folderJson.getString("name")); file.setPath(folderJson.getString("path")); file.setCreationDate(folderJson.getString("creationDate")); file.setLastModification(folderJson.getString("lastModification")); file.setTags(folderJson.getString("tags")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing remote folder : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName())); file.save(); createFolder(file.getPath(), file.getName()); allFiles.add(file); } } else { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response")); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
/** * Make remote request to get all loyalty cards stored in Cozy *///from w w w . java2 s. c om public String getRemoteExpenses() { URL urlO = null; try { urlO = new URL(designUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // 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(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() == 0) { EventBus.getDefault() .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored.")); Expense.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { try { EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE, "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "...")); JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value"); Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString()); if (expense == null) { expense = new Expense(expenseJson); } else { expense.setRemoteId(expenseJson.getString("_id")); expense.setAmount(expenseJson.getDouble("amount")); expense.setCategory(expenseJson.getString("category")); expense.setDate(expenseJson.getString("date")); if (expenseJson.has("deviceId")) { expense.setDeviceId(expenseJson.getString("deviceId")); } else { expense.setDeviceId(Device.registeredDevice().getLogin()); } } expense.save(); if (expenseJson.has("receipts")) { JSONArray receiptsArray = expenseJson.getJSONArray("receipts"); for (int j = 0; j < receiptsArray.length(); j++) { JSONObject recJsonObject = receiptsArray.getJSONObject(i); Receipt receipt = new Receipt(); receipt.setBase64(recJsonObject.getString("base64")); receipt.setExpense(expense); receipt.setName(""); receipt.save(); } } } catch (JSONException e) { EventBus.getDefault() .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage)); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } return errorMessage; }
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 w w w . j ava 2 s. co 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(), 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; } }