List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:org.apache.flink.test.util.TestBaseUtils.java
public static String getFromHTTP(String url) throws Exception { URL u = new URL(url); LOG.info("Accessing URL " + url + " as URL: " + u); HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.setConnectTimeout(100000); connection.connect();// w w w. java2 s .c o m InputStream is; if (connection.getResponseCode() >= 400) { // error! LOG.warn("HTTP Response code when connecting to {} was {}", url, connection.getResponseCode()); is = connection.getErrorStream(); } else { is = connection.getInputStream(); } return IOUtils.toString(is, connection.getContentEncoding() != null ? connection.getContentEncoding() : "UTF-8"); }
From source file:org.apache.felix.http.itest.BaseIntegrationTest.java
protected static void assertContent(int expectedRC, String expected, URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int rc = conn.getResponseCode(); assertEquals("Unexpected response code,", expectedRC, rc); if (rc >= 200 && rc < 500) { InputStream is = null;/*w w w.j av a 2 s . c o m*/ try { is = conn.getInputStream(); assertEquals(expected, slurpAsString(is)); } finally { close(is); conn.disconnect(); } } else { InputStream is = null; try { is = conn.getErrorStream(); assertEquals(expected, slurpAsString(is)); } finally { close(is); conn.disconnect(); } } }
From source file:common.net.volley.toolbox.HurlStack.java
/** * Initializes an {@link org.apache.http.HttpEntity} from the given {@link java.net.HttpURLConnection}. * @param connection/*from w w w .j ava 2 s . co m*/ * @return an HttpEntity populated with data from <code>connection</code>. */ private static HttpEntity entityFromConnection(HttpURLConnection connection) throws IOException { BasicHttpEntity entity = new BasicHttpEntity(); ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream rawStream = null; try { rawStream = connection.getInputStream(); rawStream = stethoManager.interpretResponseStream(rawStream); InputStream decompressedStream = applyDecompressionIfApplicable(connection, rawStream); if (decompressedStream != null) { copy(decompressedStream, out, new byte[1024]); } entity.setContent(new ByteArrayInputStream(out.toByteArray())); } catch (IOException ioe) { rawStream = connection.getErrorStream(); entity.setContent(rawStream); } finally { // if(rawStream != null) { // rawStream.close(); // } } entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:com.qpark.eip.core.spring.security.https.HttpsRequester.java
private static String read(final URL url, final String httpAuthBase64, final HostnameVerifier hostnameVerifier) throws IOException { StringBuffer sb = new StringBuffer(1024); HttpURLConnection connection = null; connection = (HttpURLConnection) url.openConnection(); if (url.getProtocol().equalsIgnoreCase("https")) { connection = (HttpsURLConnection) url.openConnection(); ((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier); }//from w w w . java 2s .co m if (httpAuthBase64 != null) { connection.setRequestProperty("Authorization", new StringBuffer(httpAuthBase64.length() + 6) .append("Basic ").append(httpAuthBase64).toString()); } connection.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\""); connection.setRequestMethod("GET"); int returnCode = connection.getResponseCode(); InputStream connectionIn = null; if (returnCode == 200) { connectionIn = connection.getInputStream(); } else { connectionIn = connection.getErrorStream(); } BufferedReader buffer = new BufferedReader(new InputStreamReader(connectionIn)); String inputLine; while ((inputLine = buffer.readLine()) != null) { sb.append(inputLine); } buffer.close(); return sb.toString(); }
From source file:com.memetix.gun4j.GunshortenAPI.java
protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception { final URL url = new URL(serviceUrl); final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); uc.setRequestMethod("POST"); uc.setDoOutput(true);//from w w w . j a v a 2s . c om final PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.write(paramsString); pw.close(); uc.getOutputStream().close(); try { final int responseCode = uc.getResponseCode(); final String result = inputStreamToString(uc.getInputStream()); if (responseCode != 200) { throw new Exception("Error from Gunshorten API: " + result); } return parseJSON(result); } finally { uc.getInputStream().close(); if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } } }
From source file:dlauncher.authorization.DefaultCredentialsManager.java
private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors) throws ProtocolException, IOException, AuthorizationException { JSONObject obj = null;// w w w . java 2s . c o m try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setConnectTimeout(15 * 1000); con.setReadTimeout(15 * 1000); con.connect(); try (OutputStream out = con.getOutputStream()) { out.write(post.toString().getBytes(Charset.forName("UTF-8"))); } con.getResponseCode(); InputStream instr; instr = con.getErrorStream(); if (instr == null) { instr = con.getInputStream(); } byte[] data = new byte[1024]; int length; try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) { try (InputStream in = new BufferedInputStream(instr)) { while ((length = in.read(data)) >= 0) { bytes.write(data, 0, length); } } byte[] rawBytes = bytes.toByteArray(); if (rawBytes.length != 0) { obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8"))); } else { obj = new JSONObject(); } if (!ignoreErrors && obj.has("error")) { String error = obj.getString("error"); String errorMessage = obj.getString("errorMessage"); String cause = obj.optString("cause", null); if ("ForbiddenOperationException".equals(error)) { if ("UserMigratedException".equals(cause)) { throw new UserMigratedException(errorMessage); } throw new ForbiddenOperationException(errorMessage); } throw new AuthorizationException( error + (cause != null ? "." + cause : "") + ": " + errorMessage); } return obj; } } catch (JSONException ex) { throw new InvalidResponseException(ex, obj); } }
From source file:com.zf.util.Post_NetNew.java
/** * ?// w w w.j a va 2 s . c o m * * @param pams * @param ip * @param port * @return * @throws Exception */ public static String pn(Map<String, String> pams, String ip, int port) throws Exception { if (null == pams) { return ""; } InetSocketAddress addr = new InetSocketAddress(ip, port); Proxy proxy = new Proxy(Type.HTTP, addr); String strtmp = "url"; URL url = new URL(pams.get(strtmp)); pams.remove(strtmp); strtmp = "body"; String body = pams.get(strtmp); pams.remove(strtmp); strtmp = "POST"; if (StringUtils.isEmpty(body)) strtmp = "GET"; HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy); httpConn.setConnectTimeout(30000); httpConn.setReadTimeout(30000); httpConn.setUseCaches(false); httpConn.setRequestMethod(strtmp); for (String pam : pams.keySet()) { httpConn.setRequestProperty(pam, pams.get(pam)); } if ("POST".equals(strtmp)) { httpConn.setDoOutput(true); httpConn.setDoInput(true); DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream()); dos.writeBytes(body); dos.flush(); } int resultCode = httpConn.getResponseCode(); StringBuilder sb = new StringBuilder(); sb.append(resultCode).append("\n"); String readLine; InputStream stream; try { stream = httpConn.getInputStream(); } catch (Exception ignored) { stream = httpConn.getErrorStream(); } try { BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } } catch (Exception ignored) { } return sb.toString(); }
From source file:net.technicpack.launchercore.auth.AuthenticationService.java
private static String postJson(String url, String data) throws IOException { byte[] rawData = data.getBytes("UTF-8"); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setUseCaches(false);//from www. j a va 2 s . co m connection.setDoOutput(true); connection.setDoInput(true); connection.setConnectTimeout(15000); connection.setReadTimeout(15000); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setRequestProperty("Content-Length", rawData.length + ""); connection.setRequestProperty("Content-Language", "en-US"); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.write(rawData); writer.flush(); writer.close(); InputStream stream = null; String returnable = null; try { stream = connection.getInputStream(); returnable = IOUtils.toString(stream); } catch (IOException e) { stream = connection.getErrorStream(); if (stream == null) { throw e; } } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return returnable; }
From source file:com.heraldapp.share.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * //from ww w . ja v a 2s. c om * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } String response = ""; HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); conn.setReadTimeout(10000); conn.setConnectTimeout(10000); if (!method.equals("GET")) { // use method override params.putString("method", method); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } catch (SocketTimeoutException e) { return response; } return response; }
From source file:com.pubkit.network.PubKitNetwork.java
public static JSONObject sendPost(String apiKey, JSONObject jsonObject) { URL url;//from w w w .j a v a 2s . c om HttpURLConnection connection = null; try { //Create connection url = new URL(PUBKIT_API_URL); String encodedData = jsonObject.toString(); byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length)); connection.setRequestProperty("api_key", apiKey); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(encodedData);//set data wr.flush(); //Get Response InputStream inputStream = connection.getErrorStream(); //first check for error. if (inputStream == null) { inputStream = connection.getInputStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } wr.close(); rd.close(); String responseString = response.toString(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return new JSONObject("{'error':'" + responseString + "'}"); } else { try { return new JSONObject(responseString); } catch (JSONException e) { Log.e("PUBKIT", "Error parsing data", e); } } } catch (Exception e) { Log.e("PUBKIT", "Network exception:", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }