List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java
private void drainOutput(HttpURLConnection conn) throws IOException { // for things like unauthorised (401) we won't have any content and getting the inputStream will // cause an IOException as we are in error - but there is no really way to tell this so check the // length instead. if (conn.getContentLength() > 0) { if (conn.getContentLength() < 1024) { byte[] data = new byte[conn.getConnectTimeout()]; }//from w ww . j a v a 2s . c o m if (conn.getErrorStream() != null) { IOUtils.skip(conn.getErrorStream(), conn.getContentLength()); } else { IOUtils.skip(conn.getInputStream(), conn.getContentLength()); } } }
From source file:fr.zcraft.zbanque.network.PacketSender.java
private static HTTPResponse makeRequest(String url, PacketPlayOut.PacketType method, String data) throws Throwable { // *** REQUEST *** final URL urlObj = new URL(url); final HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod(method.name()); connection.setRequestProperty("User-Agent", USER_AGENT); authenticateRequest(connection);// ww w .j a va 2s .co m connection.setDoOutput(true); try { try { connection.connect(); } catch (IOException ignored) { } if (method == PacketPlayOut.PacketType.POST) { DataOutputStream out = null; try { out = new DataOutputStream(connection.getOutputStream()); if (data != null) out.writeBytes(data); out.flush(); } finally { if (out != null) out.close(); } } // *** RESPONSE *** int responseCode; boolean failed = false; try { responseCode = connection.getResponseCode(); } catch (IOException e) { // HttpUrlConnection will throw an IOException if any 4XX // response is sent. If we request the status again, this // time the internal status will be properly set, and we'll be // able to retrieve it. // Thanks to Iigo. responseCode = connection.getResponseCode(); failed = true; } BufferedReader in = null; String body = ""; try { InputStream stream; try { stream = connection.getInputStream(); } catch (IOException e) { // Same as before stream = connection.getErrorStream(); failed = true; } in = new BufferedReader(new InputStreamReader(stream)); StringBuilder responseBuilder = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { responseBuilder.append(inputLine); } body = responseBuilder.toString(); } finally { if (in != null) in.close(); } HTTPResponse response = new HTTPResponse(); response.setResponseCode(responseCode, failed); response.setResponseBody(body); int i = 0; String headerName, headerContent; while ((headerName = connection.getHeaderFieldKey(i)) != null) { headerContent = connection.getHeaderField(i); response.addHeader(headerName, headerContent); } // *** REDIRECTION *** switch (responseCode) { case 301: case 302: case 307: case 308: if (response.getHeaders().containsKey("Location")) { response = makeRequest(response.getHeaders().get("Location"), method, data); } } // *** END *** return response; } finally { connection.disconnect(); } }
From source file:org.andstatus.app.net.http.HttpConnectionOAuthJavaNet.java
@Override protected void postRequest(HttpReadResult result) throws ConnectionException { try {//from w w w . j ava2 s . c o m HttpURLConnection conn = (HttpURLConnection) result.getUrlObj().openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); if (!result.hasFormParams()) { // Nothing to do at this step } else if (result.getFormParams().has(HttpConnection.KEY_MEDIA_PART_URI)) { writeMedia(conn, result.getFormParams()); } else { writeJson(conn, result.getFormParams()); } result.setStatusCode(conn.getResponseCode()); switch (result.getStatusCode()) { case OK: result.strResponse = HttpConnectionUtils.readStreamToString(conn.getInputStream()); break; default: result.strResponse = HttpConnectionUtils.readStreamToString(conn.getErrorStream()); throw result.getExceptionFromJsonErrorResponse(); } } catch (JSONException | IOException e) { result.e1 = e; } }
From source file:acc.healthapp.notification.HttpRequest.java
/** * Post the request// w ww.ja v a 2 s. c o m * @param url where to post to * @param requestBody the body of the request * @throws IOException */ public void doPost(String url, String requestBody) throws IOException { Log.i("", "HTTP request. body: " + requestBody); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(requestBody.getBytes().length); conn.setRequestMethod("POST"); for (int i = 0; i < mHeaders.size(); i++) { conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i)); } OutputStream out = null; try { out = conn.getOutputStream(); out.write(requestBody.getBytes()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore. } } } responseCode = conn.getResponseCode(); InputStream inputStream = null; try { if (responseCode == 200) { inputStream = conn.getInputStream(); } else { inputStream = conn.getErrorStream(); } responseBody = getString(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // Ignore. } } } Log.i("", "HTTP response. body: " + responseBody); conn.disconnect(); }
From source file:com.tdevelopers.questo.Pushes.HttpRequest.java
/** * Post the request// w w w . ja v a2s .c om * * @param url where to post to * @param requestBody the body of the request * @throws IOException */ public void doPost(String url, String requestBody) throws IOException { Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody); Log.i(LoggingService.LOG_TAG, "header" + mHeaders.toString()); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(requestBody.getBytes().length); conn.setRequestMethod("POST"); for (int i = 0; i < mHeaders.size(); i++) { conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i)); } OutputStream out = null; try { out = conn.getOutputStream(); out.write(requestBody.getBytes()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore. } } } responseCode = conn.getResponseCode(); InputStream inputStream = null; try { if (responseCode == 200) { inputStream = conn.getInputStream(); } else { inputStream = conn.getErrorStream(); } responseBody = getString(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // Ignore. } } } Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody); conn.disconnect(); }
From source file:com.google.android.gcm.demo.logic.HttpRequest.java
/** * Post the request// w w w . j a v a2s. c o m * @param url where to post to * @param requestBody the body of the request * @throws IOException */ public void doPost(String url, String requestBody) throws IOException { Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(requestBody.getBytes().length); conn.setRequestMethod("POST"); for (int i = 0; i < mHeaders.size(); i++) { conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i)); } OutputStream out = null; try { out = conn.getOutputStream(); out.write(requestBody.getBytes()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore. } } } responseCode = conn.getResponseCode(); InputStream inputStream = null; try { if (responseCode == 200) { inputStream = conn.getInputStream(); } else { inputStream = conn.getErrorStream(); } responseBody = getString(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // Ignore. } } } Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody); conn.disconnect(); }
From source file:com.nkc.nkcpost.helper.HttpRequest.java
/** * Post the request// ww w . j av a 2 s. c o m * * @param url where to post to * @param requestBody the body of the request * @throws IOException */ public void doPost(String url, String requestBody) throws IOException { //Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(requestBody.getBytes().length); conn.setRequestMethod("POST"); for (int i = 0; i < mHeaders.size(); i++) { conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i)); } OutputStream out = null; try { out = conn.getOutputStream(); out.write(requestBody.getBytes()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore. } } } responseCode = conn.getResponseCode(); InputStream inputStream = null; try { if (responseCode == 200) { inputStream = conn.getInputStream(); } else { inputStream = conn.getErrorStream(); } responseBody = getString(inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // Ignore. } } } //Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody); conn.disconnect(); }
From source file:br.bireme.accounts.Authentication.java
public JSONObject getUser(final String user, final String password) throws IOException, ParseException { if (user == null) { throw new NullPointerException("user"); }/*from w w w . j a va 2 s . co m*/ if (password == null) { throw new NullPointerException("password"); } final JSONObject parameters = new JSONObject(); parameters.put("username", user); parameters.put("password", password); parameters.put("service", SERVICE_NAME); parameters.put("format", "json"); //final URL url = new URL("http", host, port, DEFAULT_PATH); final URL url = new URL("http://" + host + DEFAULT_PATH); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); final StringBuilder builder = new StringBuilder(); final BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); //final String message = parameters.toJSONString(); //System.out.println(message); writer.write(parameters.toJSONString()); writer.newLine(); writer.close(); final int respCode = connection.getResponseCode(); final boolean respCodeOk = (respCode == 200); final BufferedReader reader; if (respCodeOk) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); } else { reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); } while (true) { final String line = reader.readLine(); if (line == null) { break; } builder.append(line); builder.append("\n"); } reader.close(); if (!respCodeOk && (respCode != 401)) { throw new IOException(builder.toString()); } return (JSONObject) new JSONParser().parse(builder.toString()); }
From source file:cz.vutbr.fit.xzelin15.dp.consumer.WSDynamicClientFactory.java
private String transferWSDL(String wsdlURL, String userPassword, WiseProperties wiseProperties) throws WiseConnectionException { String filePath = null;/*w ww. j ava 2s. c om*/ try { URL endpoint = new URL(wsdlURL); // Create the connection HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); // set Connection close, otherwise we get a keep-alive // connection // that gives us fragmented answers. conn.setRequestProperty("Connection", "close"); // BASIC AUTH if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } // Read response InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } // saving file File file = new File(wiseProperties.getProperty("wise.tmpDir"), new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
From source file:me.figo.FigoConnection.java
/*** * Helper method for making a OAuth2-compliant API call * /*ww w. j a va 2s .com*/ * @param path path on the server to call * @param data Payload of the request * @param typeofT Type of expected response * @return * @throws IOException * @throws FigoException */ public <T> T queryApi(String path, Object data, String method, Type typeOfT) throws IOException, FigoException { URL url = new URL(API_ENDPOINT + path); // configure URL connection, i.e. the HTTP request HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Authorization", "Basic " + this.basicAuthInfo); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // add payload if (data != null) { String encodedData = GsonAdapter.createGson().toJson(data); connection.setDoOutput(true); connection.getOutputStream().write(encodedData.getBytes("UTF-8")); } // process response int code = connection.getResponseCode(); if (code >= 200 && code < 300) { return handleResponse(connection.getInputStream(), typeOfT); } else if (code == 400) { throw new FigoException( (ErrorResponse) handleResponse(connection.getErrorStream(), FigoException.ErrorResponse.class)); } else if (code == 401) { throw new FigoException("access_denied", "Access Denied"); } else { //return decode(connection.getErrorStream(), resultType); throw new FigoException("internal_server_error", "We are very sorry, but something went wrong"); } }