List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.portfolio.data.attachment.XSLService.java
void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer) throws MalformedURLException, IOException { /// Receive answer InputStream in;/*from www .ja v a2 s .c o m*/ try { in = connection.getInputStream(); } catch (Exception e) { System.out.println(e.toString()); in = connection.getErrorStream(); } String ref = null; if (referer != null) { int first = referer.indexOf('/', 7); int last = referer.lastIndexOf('/'); ref = referer.substring(first, last); } response.setContentType(connection.getContentType()); response.setStatus(connection.getResponseCode()); response.setContentLength(connection.getContentLength()); /// Transfer headers Map<String, List<String>> headers = connection.getHeaderFields(); int size = headers.size(); for (int i = 1; i < size; ++i) { String key = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); // response.setHeader(key, value); response.addHeader(key, value); } /// Deal with correct path with set cookie List<String> setValues = headers.get("Set-Cookie"); if (setValues != null) { String setVal = setValues.get(0); int pathPlace = setVal.indexOf("Path="); if (pathPlace > 0) { setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break setVal = setVal + ref; response.setHeader("Set-Cookie", setVal); } } /// Write back data DataInputStream stream = new DataInputStream(in); byte[] buffer = new byte[1024]; // int size; ServletOutputStream out = null; try { out = response.getOutputStream(); while ((size = stream.read(buffer, 0, buffer.length)) != -1) out.write(buffer, 0, size); } catch (Exception e) { System.out.println(e.toString()); System.out.println("Writing messed up!"); } finally { in.close(); out.flush(); // close() should flush already, but Tomcat 5.5 doesn't out.close(); } }
From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java
@Test public void multipleValuesInAcceptHeaderWithIncorrectCharset() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json," + "application/json;q=0.1,application/json;charset=utf<8"); connection.connect();/*from ww w. j a va 2 s . c o m*/ assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content.contains( "The charset specified in Accept header " + "'application/json;charset=utf<8' is not supported.")); }
From source file:eu.codeplumbers.cosi.services.CosiSmsService.java
private List<Sms> getRemoteMessages() { allSms.clear();/* w w w. j a v a 2 s. c o m*/ 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 SmsSyncEvent(SYNC_MESSAGE, "Your Cozy has no Text messages stored.")); Sms.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { mBuilder.setProgress(jsonArray.length(), i, false); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_cozy))); JSONObject smsJson = jsonArray.getJSONObject(i).getJSONObject("value"); Sms sms = Sms.getBySystemIdAddressAndBody(smsJson.get("systemId").toString(), smsJson.getString("address"), smsJson.getString("body")); if (sms == null) { sms = new Sms(smsJson); } else { sms.setRemoteId(smsJson.getString("_id")); sms.setSystemId(smsJson.getString("systemId")); sms.setAddress(smsJson.getString("address")); sms.setBody(smsJson.getString("body")); if (smsJson.has("readState")) { sms.setReadState(smsJson.getBoolean("readState")); } sms.setDateAndTime(smsJson.getString("dateAndTime")); sms.setType(smsJson.getInt("type")); } sms.save(); allSms.add(sms); } } } else { errorMessage = "Failed to parse API response"; EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, "Failed to parse API response")); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (JSONException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } return allSms; }
From source file:com.ehsy.solr.util.SimplePostTool.java
private static boolean checkResponseCode(HttpURLConnection urlc) throws IOException { if (urlc.getResponseCode() >= 400) { warn("Solr returned an error #" + urlc.getResponseCode() + " (" + urlc.getResponseMessage() + ") for url: " + urlc.getURL()); Charset charset = StandardCharsets.ISO_8859_1; final String contentType = urlc.getContentType(); // code cloned from ContentStreamBase, but post.jar should be standalone! if (contentType != null) { int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset="); if (idx > 0) { charset = Charset.forName(contentType.substring(idx + "charset=".length()).trim()); }/*from www . ja v a2s . c om*/ } // Print the response returned by Solr try (InputStream errStream = urlc.getErrorStream()) { if (errStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(errStream, charset)); final StringBuilder response = new StringBuilder("Response: "); int ch; while ((ch = br.read()) != -1) { response.append((char) ch); } warn(response.toString().trim()); } } return false; } return true; }
From source file:com.apache.ivy.BasicURLHandler.java
/** * Read and ignore the response body. /*from www . ja va 2 s . co m*/ */ private void readResponseBody(HttpURLConnection conn) { byte[] buffer = new byte[BUFFER_SIZE]; InputStream inStream = null; try { inStream = conn.getInputStream(); while (inStream.read(buffer) > 0) { //Skip content } } catch (IOException e) { // ignore } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { // ignore } } } InputStream errStream = conn.getErrorStream(); if (errStream != null) { try { while (errStream.read(buffer) > 0) { //Skip content } } catch (IOException e) { // ignore } finally { try { errStream.close(); } catch (IOException e) { // ignore } } } }
From source file:gov.medicaid.verification.BaseSOAPClient.java
/** * Invokes the web service using the request provided. * * @param serviceURL the end point reference * @param original the payload//from ww w .j av a 2 s. c o m * @return the response * @throws IOException for IO errors while executing the request * @throws TransformerException for any transformation errors */ protected String invoke(String serviceURL, String original) throws IOException, TransformerException { URL url = new URL(serviceURL); HttpURLConnection rc = (HttpURLConnection) url.openConnection(); rc.setRequestMethod("POST"); rc.setDoOutput(true); rc.setDoInput(true); rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); System.out.println("before transform:" + original); String request = transform(requestXSLT, original); System.out.println("after transform:" + request); int len = request.length(); rc.setRequestProperty("Content-Length", Integer.toString(len)); rc.connect(); OutputStreamWriter out = new OutputStreamWriter(rc.getOutputStream()); out.write(request, 0, len); out.flush(); InputStreamReader read; try { read = new InputStreamReader(rc.getInputStream()); } catch (IOException e) { read = new InputStreamReader(rc.getErrorStream()); } try { String response = IOUtils.toString(read); System.out.println("actual result:" + response); String transformedResponse = transform(responseXSLT, response); System.out.println("transformed result:" + transformedResponse); return transformedResponse; } finally { read.close(); rc.disconnect(); } }
From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java
@Test public void supportedAcceptHeaderWithUnSupportedAcceptCharsetHeader() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "iso-8859-1"); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;charset=utf8"); connection.connect();//from w w w .j a v a2s . c o m assertEquals(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content .contains("The charset specified in Accept charset header " + "'iso-8859-1' is not supported.")); }
From source file:com.bigstep.datalake.DLFileSystem.java
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream) throws IOException { if (c.getContentLength() == 0) { return null; }//w w w . j a v a 2s .com final InputStream in = useErrorStream ? c.getErrorStream() : c.getInputStream(); if (in == null) { throw new IOException("The " + (useErrorStream ? "error" : "input") + " stream is null."); } try { final String contentType = c.getContentType(); if (contentType != null) { final MediaType parsed = MediaType.valueOf(contentType); if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) { throw new IOException("Content-Type \"" + contentType + "\" is incompatible with \"" + MediaType.APPLICATION_JSON + "\" (parsed=\"" + parsed + "\")"); } } final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Gson gson = new Gson(); return gson.fromJson(reader, Map.class); } finally { in.close(); } }
From source file:org.jongo.mocks.JongoClient.java
private JongoResponse doRequest(final String url, final List<NameValuePair> parameters) { final String urlParameters = URLEncodedUtils.format(parameters, "UTF-8"); JongoResponse response = null;/* w w w. j a va 2s . c o m*/ try { HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", MediaType.APPLICATION_XML); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader r = null; if (con.getResponseCode() != Response.Status.CREATED.getStatusCode()) { r = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { r = new BufferedReader(new InputStreamReader(con.getInputStream())); } StringBuilder rawresponse = new StringBuilder(); String strLine = null; while ((strLine = r.readLine()) != null) { rawresponse.append(strLine); rawresponse.append("\n"); } try { response = XmlXstreamTest.successFromXML(rawresponse.toString()); } catch (Exception e) { response = XmlXstreamTest.errorFromXML(rawresponse.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return response; }
From source file:com.spinn3r.api.BaseClient.java
/** * Fetch the API with the given FeedConfig * /*from ww w .j a v a 2 s.co m*/ * @throws IOException if there's an error with network transport. * @throws ParseException if there's a problem parsing the resulting XML. */ private PartialBaseClientResult<ResultType> startFetch(Config<ResultType> config, int request_limit) throws IOException, InterruptedException { PartialBaseClientResult<ResultType> result = new PartialBaseClientResult<ResultType>(config); if (config.getVendor() == null) throw new RuntimeException("Vendor not specified"); String resource = config.getNextRequestURL(); //enforce max limit so that we don't generate runtime exceptions. if (request_limit > config.getMaxLimit()) request_limit = config.getMaxLimit(); if (resource == null) { resource = config.getFirstRequestURL(); // if the API has NEVER been used before then generate the first // request URL from the config parameters. if (resource == null) resource = config.generateFirstRequestURL(request_limit); } //apply the request_limit to the current URL. This needs to be done so //that we can change the limit at runtime. When I originally designed //the client I didn't want to support introspecting and mutating the URL //on the client but with the optimial limit performance optimization //this is impossible. resource = setParam(resource, "limit", request_limit); // add a connection number to the vendor code resource = addConnectionNumber(resource); // store the last requested URL so we can expose this to the caller for // debug purposes. result.setLastRequestURL(resource); result.setRequestLimit(request_limit); URLConnection conn = getConnection(resource); /* * If this is an http connection and there is an error code, * return throw an error message containing the response * message. */ if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); if (responseCode >= 400) { StringBuilder message = new StringBuilder(""); InputStream errorStream = httpConn.getErrorStream(); if (errorStream == null) throw new IOException(String.format("Response code %d received", responseCode)); BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(errorStream))); String line; while ((line = reader.readLine()) != null) message.append(line); throw new IOException(message.toString()); } } result.setConnection(conn); setMoreResults(conn, result); result.setNextRequestURL(conn.getHeaderField("X-Next-Request-URL")); return result; }