List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.github.gorbin.asne.linkedin.LinkedInSocialNetwork.java
private String checkInputStream(HttpURLConnection connection) { String code = null, errorMessage = null; InputStream inputStream = connection.getErrorStream(); String response = streamToString(inputStream); try {//from w w w . ja v a2 s . co m JSONObject jsonResponse = (JSONObject) new JSONTokener(response).nextValue(); if (jsonResponse.has("status")) { code = jsonResponse.getString("status"); } if (jsonResponse.has("message")) { errorMessage = jsonResponse.getString("message"); } return "ERROR CODE: " + code + " ERROR MESSAGE: " + errorMessage; } catch (JSONException e) { return e.getMessage(); } }
From source file:manchester.synbiochem.datacapture.SeekConnector.java
private void readErrorFromConnection(HttpURLConnection c, String logPrefix, String message) throws IOException { int rc = c.getResponseCode(); String msg = c.getResponseMessage(); log.error(logPrefix + ": " + rc + " " + msg); InputStream errors = c.getErrorStream(); if (errors != null) { for (String line : readLines(errors)) log.error(logPrefix + ": " + line); errors.close();//from w w w.jav a2s . co m } throw new InternalServerErrorException(format(message, rc, msg)); }
From source file:com.ijiaban.uitls.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. *//* w w w . jav a 2s. c om*/ 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 == HttpURLConnection.HTTP_OK) { InputStream is = con.getInputStream(); String detail = readResponse(is); JSONObject jb = new JSONObject(detail); String name = getFirstName(detail); String image = getImage(detail); mFragment.show("Welcome " + name + "!"); mFragment.displayimage(image); is.close(); return; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mFragment.getActivity(), 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.parasoft.em.client.impl.JSONClient.java
protected JSONObject doPost(String restPath, JSONObject payload) throws IOException { HttpURLConnection connection = getConnection(restPath); connection.setRequestMethod("POST"); if (payload != null) { String payloadString = payload.toString(); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); BufferedOutputStream stream = new BufferedOutputStream(connection.getOutputStream()); try {// w w w . ja v a 2 s .c om byte[] bytes = payloadString.getBytes("UTF-8"); stream.write(bytes, 0, bytes.length); } finally { stream.close(); } } int responseCode = connection.getResponseCode(); if (responseCode / 100 == 2) { return getResponseJSON(connection.getInputStream()); } else { String errorMessage = getResponseString(connection.getErrorStream()); throw new IOException(restPath + ' ' + responseCode + '\n' + errorMessage); } }
From source file:com.example.appengine.appidentity.UrlShortener.java
/** * Returns a shortened URL by calling the Google URL Shortener API. * * <p>Note: Error handling elided for simplicity. *//* w ww . j a v a 2s .c o m*/ public String createShortUrl(String longUrl) throws Exception { ArrayList<String> scopes = new ArrayList<String>(); scopes.add("https://www.googleapis.com/auth/urlshortener"); final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); // The token asserts the identity reported by appIdentity.getServiceAccountName() JSONObject request = new JSONObject(); request.put("longUrl", longUrl); URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken()); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); request.write(writer); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Note: Should check the content-encoding. // Any JSON parser can be used; this one is used for illustrative purposes. JSONTokener responseTokens = new JSONTokener(connection.getInputStream()); JSONObject response = new JSONObject(responseTokens); return (String) response.get("id"); } else { try (InputStream s = connection.getErrorStream(); InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) { throw new RuntimeException(String.format("got error (%d) response %s from %s", connection.getResponseCode(), CharStreams.toString(r), connection.toString())); } } }
From source file:com.mycompany.grupo6ti.GenericResource.java
@GET @Produces("application/json") @Path("/obtenerFactura/{id}") public String obtenerFactura(@PathParam("id") String id) { String result = " "; try {/* w w w. j a v a 2 s . c om*/ String line; URL url = new URL("http://localhost:85/" + id); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is; conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("GET"); conn.setDoInput(true); if (conn.getResponseCode() >= 400) { is = conn.getErrorStream(); } else { is = conn.getInputStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); while ((line = rd.readLine()) != null) { result += line; } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:at.ac.tuwien.dsg.celar.mela.jCatascopiaClient.JCatascopiaDataSource.java
/** * Example of JSON to parse/*from w w w . j av a 2s. c o m*/ * {"agents":[{"agentID":"7d2c9d18cc694ea7b7f0ea8002773871","agentIP":"10.16.21.73","status":"UP"} * ,{"agentID":"9e14d7ee11414641994cc3563f6b37d9","agentIP":"10.16.21.52","status":"UP"}} */ private void updateJCatascopiaAgents(List<JCatascopiaAgent> agentsPool) { URL url = null; HttpURLConnection connection = null; try { url = new URL(this.url + "/agents"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); String line; while ((line = reader.readLine()) != null) { Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, line); } } InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String agentsDescription = ""; String line = ""; while ((line = bufferedReader.readLine()) != null) { agentsDescription += line; } JSONObject object = new JSONObject(agentsDescription); if (object.has("agents")) { JSONArray agents = object.getJSONArray("agents"); int nrOfAgentsInJCatascopia = agents.length(); int nrOfAgentsInPool = agentsPool.size(); int sizeDifference = nrOfAgentsInPool - nrOfAgentsInJCatascopia; //resize agents pool if (sizeDifference < 0) { //inchrease agents pool for (int i = sizeDifference; i < 0; i++) { agentsPool.add(new JCatascopiaAgent()); } } else if (sizeDifference > 0) { for (int i = sizeDifference; i > 0; i--) { agentsPool.remove(0); } } //populate the agents pool for (int i = 0; i < agents.length(); i++) { JSONObject agent = agents.getJSONObject(i); JCatascopiaAgent jCatascopiaAgent = agentsPool.get(i); //get agent ID if (agent.has("agentID")) { jCatascopiaAgent.setId(agent.getString("agentID")); } else { Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, "JCatascopia agentID not found in {0}", agentsDescription); } //get agent IP if (agent.has("agentIP")) { jCatascopiaAgent.setIp(agent.getString("agentIP")); } else { Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, "JCatascopia agentIP not found in {0}", agentsDescription); } //get agent status if (agent.has("status")) { jCatascopiaAgent.setStatus(agent.getString("status")); } else { Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, "JCatascopia status not found in {0}", agentsDescription); } } } else { Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, "No JCatascopia agents found in {0}", agentsDescription); } } catch (Exception e) { Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, "Error connecting to " + this.url); Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, e.getMessage(), e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java
/** * Invokes the given method with the given arguments and returns * an object of the given type, or null if void. * * @see JsonRpcClient#writeRequest(String, Object, java.io.OutputStream, String) * @param methodName the name of the method to invoke * @param arguments the arguments to the method * @param returnType the return type//w ww .j a v a 2s . co m * @param extraHeaders extra headers to add to the request * @return the return value * @throws Throwable on error */ public Object invoke(String methodName, Object argument, Type returnType, Map<String, String> extraHeaders) throws Throwable { // create URLConnection HttpURLConnection con = prepareConnection(extraHeaders); con.connect(); // invoke it OutputStream ops = con.getOutputStream(); try { super.invoke(methodName, argument, ops); } finally { ops.close(); } // read and return value try { InputStream ips = con.getInputStream(); try { // in case of http error try to read response body and return it in exception return super.readResponse(returnType, ips); } finally { ips.close(); } } catch (IOException e) { throw new HttpException(readString(con.getErrorStream()), e); } }
From source file:io.confluent.kafkarest.tools.ConsumerPerformance.java
private <T> T request(String target, String method, byte[] entity, String entityLength, TypeReference<T> responseFormat) { HttpURLConnection connection = null; try {// w ww. j ava 2 s. co m URL url = new URL(target); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); if (entity != null) { connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT); connection.setRequestProperty("Content-Length", entityLength); } connection.setDoInput(true); connection.setUseCaches(false); if (entity != null) { connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); os.write(entity); os.flush(); os.close(); } int responseStatus = connection.getResponseCode(); if (responseStatus >= 400) { InputStream es = connection.getErrorStream(); ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class); es.close(); throw new RuntimeException(String.format("Unexpected HTTP error status %d for %s request to %s: %s", responseStatus, method, target, errorMessage.getMessage())); } if (responseStatus != HttpURLConnection.HTTP_NO_CONTENT) { InputStream is = connection.getInputStream(); T result = serializer.readValue(is, responseFormat); is.close(); return result; } return null; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:edu.purdue.cybercenter.dm.storage.GlobusStorageFileManager.java
private Map<String, Object> getResponse(HttpURLConnection connection) throws IOException { Map<String, Object> response; int responseCode = connection.getResponseCode(); System.out.println("response code: " + responseCode); if (responseCode >= 200 && responseCode < 300) { InputStream inputStream = connection.getInputStream(); String input = IOUtils.toString(inputStream); response = Helper.deserialize(input, Map.class); } else {/*from ww w . j a v a2s . c o m*/ InputStream errorStream = connection.getErrorStream(); String error = IOUtils.toString(errorStream); response = Helper.deserialize(error, Map.class); } return response; }