List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java
public static void main(String[] args) { try {//from ww w .ja v a2 s.co m String url = "http://localhost:8080/scim/v2/Groups"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Setting basic post request con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/scim+json"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(createRequestBody); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode == HttpURLConnection.HTTP_CREATED) { // success in = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //printing result from response System.out.println("Response Code : " + responseCode); System.out.println("Response Message : " + con.getResponseMessage()); System.out.println("Response Content : " + response.toString()); } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.wso2.charon3.samples.user.sample01.CreateUserSample.java
public static void main(String[] args) { try {/*from w ww. j a va 2 s .c o m*/ String url = "http://localhost:8080/scim/v2/Users"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Setting basic post request con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/scim+json"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(createRequestBody); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode == HttpURLConnection.HTTP_CREATED) { // success in = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //printing result from response System.out.println("Response Code : " + responseCode); System.out.println("Response Message : " + con.getResponseMessage()); System.out.println("Response Content : " + response.toString()); } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:OCRRestAPI.java
public static void main(String[] args) throws Exception { /*/*from ww w . j a v a 2 s. c om*/ Sample project for OCRWebService.com (REST API). Extract text from scanned images and convert into editable formats. Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code */ // Provide your user name and license code String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D"; String user_name = "FERGOID"; /* You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide Input parameters: [language] - Specifies the recognition language. This parameter can contain several language names separated with commas. For example "language=english,german,spanish". Optional parameter. By default:english [pagerange] - Enter page numbers and/or page ranges separated by commas. For example "pagerange=1,3,5-12" or "pagerange=allpages". Optional parameter. By default:allpages [tobw] - Convert image to black and white (recommend for color image and photo). For example "tobw=false" Optional parameter. By default:false [zone] - Specifies the region on the image for zonal OCR. The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. This parameter can contain several zones separated with commas. For example "zone=0:0:100:100,50:50:50:50" Optional parameter. [outputformat] - Specifies the output file format. Can be specified up to two output formats, separated with commas. For example "outputformat=pdf,txt" Optional parameter. By default:doc [gettext] - Specifies that extracted text will be returned. For example "tobw=true" Optional parameter. By default:false [description] - Specifies your task description. Will be returned in response. Optional parameter. !!!! For getting result you must specify "gettext" or "outputformat" !!!! */ // Build your OCR: // Extraction text with English language String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true"; // Extraction text with English and German language using zonal OCR ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400"; // Convert first 5 pages of multipage document into doc and txt // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt"; // Full path to uploaded document String filePath = "sarah-morgan.jpg"; byte[] fileContent = Files.readAllBytes(Paths.get(filePath)); URL url = new URL(ocrURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes())); // Specify Response format to JSON or XML (application/json or application/xml) connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length)); int httpCode; try (OutputStream stream = connection.getOutputStream()) { // Send POST request stream.write(fileContent); stream.close(); } catch (Exception e) { System.out.println(e.toString()); } httpCode = connection.getResponseCode(); System.out.println("HTTP Response code: " + httpCode); // Success request if (httpCode == HttpURLConnection.HTTP_OK) { // Get response stream String jsonResponse = GetResponseToString(connection.getInputStream()); // Parse and print response from OCR server PrintOCRResponse(jsonResponse); } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("OCR Error Message: Unauthorizied request"); } else { // Error occurred String jsonResponse = GetResponseToString(connection.getErrorStream()); JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); // Error message System.out.println("Error Message: " + jsonObj.get("ErrorMessage")); } connection.disconnect(); }
From source file:Main.java
/** * Extract the error of an HTTP response as a string. * @param connection the connection to read from. * @return the string extracted from the connection's error stream. * @throws Exception if any error occurs. *//*from ww w . j a v a 2s. c om*/ static String readErrorBody(HttpURLConnection connection) throws Exception { return readString(new BufferedInputStream(connection.getErrorStream())); }
From source file:com.checkoutcrypto.api.HttpUtils.java
public static String getErrorResponse(HttpURLConnection urlConnection) { InputStream errorStream = urlConnection.getErrorStream(); try {/*from w w w. j a v a2s.com*/ if (errorStream != null) { byte[] responseBytes = getContent(errorStream).toByteArray(); return new String(responseBytes, "UTF-8"); } } catch (IOException e) { return "Failed to get error response: " + e.getLocalizedMessage(); } return null; }
From source file:org.droidparts.http.worker.HTTPInputStream.java
public static HTTPInputStream getInstance(HttpURLConnection conn, boolean useErrorStream) throws HTTPException { try {/* w w w . j a v a 2s .c o m*/ InputStream is = useErrorStream ? conn.getErrorStream() : conn.getInputStream(); is = getUnpackedInputStream(conn.getContentEncoding(), is); return new HTTPInputStream(is, conn, null); } catch (Exception e) { throw new HTTPException(e); } }
From source file:net.ftb.util.AppUtils.java
public static String ConnectionToString(URLConnection c) { boolean failed = false; HttpURLConnection conn = (HttpURLConnection) c; try {//from w ww . j a v a2 s .c o m if (conn.getErrorStream() != null) { return IOUtils.toString(conn.getErrorStream(), Charsets.UTF_8); } else if (conn.getInputStream() != null) { return IOUtils.toString(conn.getInputStream(), Charsets.UTF_8); } else { return null; } } catch (FileNotFoundException e) { // ignore this } catch (IOException e) { failed = true; } catch (Exception e) { failed = true; Logger.logDebug("failed", e); } if (failed) { try { return IOUtils.toString(c.getInputStream(), Charsets.UTF_8); } catch (Exception e) { Logger.logDebug("failed", e); } } return null; }
From source file:com.camel.trainreserve.JDKHttpsClient.java
protected static String getResponseAsString(HttpURLConnection conn) throws IOException { String charset = getResponseCharset(conn.getContentType()); InputStream es = conn.getErrorStream(); if (es == null) { return getStreamAsString(conn.getInputStream(), charset); } else {/*from w w w. ja v a 2s. c o m*/ String msg = getStreamAsString(es, charset); if (StringUtils.isEmpty(msg)) { throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage()); } else { throw new IOException(msg); } } }
From source file:com.eTilbudsavis.etasdk.network.impl.HttpURLNetwork.java
private static HttpEntity getEntity(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream inputStream;//from w ww . ja v a 2 s .com try { inputStream = connection.getInputStream(); } catch (IOException ioe) { inputStream = connection.getErrorStream(); } entity.setContent(inputStream); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:com.telefonica.iot.perseo.test.Help.java
private static String getBodyResponse(HttpURLConnection con) throws IOException { int responseCode = con.getResponseCode(); InputStream stream;/*from w w w. j a v a 2 s.com*/ if (responseCode / 100 == 2) { stream = con.getInputStream(); } else { stream = con.getErrorStream(); } if (stream != null) { BufferedReader in = new BufferedReader(new InputStreamReader(stream)); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } return null; }