Java Code Examples for javax.net.ssl.HttpsURLConnection#getErrorStream()

The following examples show how to use javax.net.ssl.HttpsURLConnection#getErrorStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiPart.java    From constellation with Apache License 2.0 6 votes vote down vote up
public static byte[] getBody(final HttpsURLConnection conn, final int code) throws IOException {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    final byte[] buf = new byte[256 * 1024];
    try (final InputStream in = code / 100 == 2 ? conn.getInputStream() : conn.getErrorStream()) {
        while (true) {
            final int len = in.read(buf);
            if (len == -1) {
                break;
            }

            os.write(buf, 0, len);
        }
    }

    return os.toByteArray();
}
 
Example 2
Source File: HttpResponse.java    From jarling with MIT License 6 votes vote down vote up
public HttpResponse(HttpsURLConnection httpsURLConnection) throws StarlingBankRequestException {
    this.httpsURLConnection = httpsURLConnection;
    try {
        if (httpsURLConnection.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST){
            this.is = httpsURLConnection.getInputStream();
        }else {
            this.is = httpsURLConnection.getErrorStream();
            processStatusCode(httpsURLConnection);
        }
        this.statusCode = httpsURLConnection.getResponseCode();
        this.expiration = httpsURLConnection.getExpiration();
        this.request = httpsURLConnection.getURL();
        this.expiration = httpsURLConnection.getExpiration();
        this.lastModified = httpsURLConnection.getLastModified();
        this.responseHeaders = httpsURLConnection.getHeaderFields();
        this.contentType = httpsURLConnection.getContentType();
        this.contentEncoding = httpsURLConnection.getContentEncoding();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: Main.java    From glitchify with MIT License 6 votes vote down vote up
private JSONResponse getJSON(URL url) throws Exception {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", "Glitchify|[email protected]");
    if (url.getHost().contains("twitch.tv")) {
        conn.setRequestProperty("Client-ID", "2pvhvz6iubpg0ny77pyb1qrjynupjdu");
    }
    InputStream inStream;
    int responseCode = conn.getResponseCode();
    if (responseCode >= 400) {
        inStream = conn.getErrorStream();
    } else {
        inStream = conn.getInputStream();
    }
    BufferedReader buffReader = new BufferedReader(new InputStreamReader(inStream));
    StringBuilder jsonString = new StringBuilder();
    String line;
    while ((line = buffReader.readLine()) != null) {
        jsonString.append(line);
    }
    buffReader.close();

    return new JSONResponse(responseCode, jsonString.toString());
}
 
Example 4
Source File: Response.java    From weixin4j with Apache License 2.0 5 votes vote down vote up
public Response(HttpsURLConnection https) throws IOException {
    this.https = https;
    this.status = https.getResponseCode();
    if (null == (is = https.getErrorStream())) {
        is = https.getInputStream();
    }
}
 
Example 5
Source File: MineSkinAPI.java    From SkinsRestorerX with GNU General Public License v3.0 5 votes vote down vote up
private String queryURL(String url, String query, int timeout) throws IOException {
    for (int i = 0; i < 3; i++) { // try 3 times, if server not responding
        try {
            MetricsCounter.incrAPI(url);
            HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-length", String.valueOf(query.length()));
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("User-Agent", "SkinsRestorer");
            con.setConnectTimeout(timeout);
            con.setReadTimeout(timeout);
            con.setDoOutput(true);
            con.setDoInput(true);
            DataOutputStream output = new DataOutputStream(con.getOutputStream());
            output.writeBytes(query);
            output.close();
            String outstr = "";
            InputStream _is;
            try {
                _is = con.getInputStream();
            } catch (Exception e) {
                _is = con.getErrorStream();
            }
            DataInputStream input = new DataInputStream(_is);
            for (int c = input.read(); c != -1; c = input.read()) {
                outstr += (char) c;
            }
            input.close();
            return outstr;
        } catch (Exception ignored) {
        }
    }
    return "";
}
 
Example 6
Source File: SessionQueryAll.java    From pxgrid-rest-ws with Apache License 2.0 5 votes vote down vote up
public static void postAndStreamPrint(HttpsURLConnection httpsConn, Object postObject) throws IOException {
	Gson gson = new GsonBuilder().registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeAdapter()).create();
	httpsConn.setRequestMethod("POST");
	httpsConn.setRequestProperty("Content-Type", "application/json");
	httpsConn.setRequestProperty("Accept", "application/json");
	httpsConn.setDoInput(true);
	httpsConn.setDoOutput(true);
	OutputStreamWriter osw = new OutputStreamWriter(httpsConn.getOutputStream());
	osw.write(gson.toJson(postObject));
	osw.flush();

	int status = httpsConn.getResponseCode();
	logger.info("Response status={}", status);
	
	if (status < HttpURLConnection.HTTP_BAD_REQUEST) {
		try (InputStream in = httpsConn.getInputStream()) {
			JsonReader jreader = new JsonReader(new InputStreamReader(in));
			jreader.beginObject();
			String name = jreader.nextName();
			if ("sessions".equals(name)) {
				int count = 0;
				jreader.beginArray();
				while (jreader.hasNext()) {
					Session session = gson.fromJson(jreader, Session.class);
					System.out.println("session=" + session);
					count++;
				}
				System.out.println("count=" + count);
			}
		}
	} else {
		try (InputStream in = httpsConn.getErrorStream()) {
			String content = IOUtils.toString(in, StandardCharsets.UTF_8);
			System.out.println("Content: " + content);
		}
	}
}
 
Example 7
Source File: Gateway.java    From gateway-android-sdk with Apache License 2.0 4 votes vote down vote up
GatewayMap executeGatewayRequest(GatewayRequest request) throws Exception {
    // init connection
    HttpsURLConnection c = createHttpsUrlConnection(request);

    // encode request data to json
    String requestData = gson.toJson(request.payload);

    // log request data
    logger.logRequest(c, requestData);

    // write request data
    if (requestData != null) {
        OutputStream os = c.getOutputStream();
        os.write(requestData.getBytes("UTF-8"));
        os.close();
    }

    // initiate the connection
    c.connect();

    String responseData = null;
    int statusCode = c.getResponseCode();
    boolean isStatusOk = (statusCode >= 200 && statusCode < 300);

    // if connection has output stream, get the data
    // socket time-out exceptions will be thrown here
    if (c.getDoInput()) {
        InputStream is = isStatusOk ? c.getInputStream() : c.getErrorStream();
        responseData = inputStreamToString(is);
        is.close();
    }

    c.disconnect();

    // log response
    logger.logResponse(c, responseData);

    // parse the response body
    GatewayMap response = new GatewayMap(responseData);

    // if response static is good, return response
    if (isStatusOk) {
        return response;
    }

    // otherwise, create a gateway exception and throw it
    String message = (String) response.get("error.explanation");
    if (message == null) {
        message = "An error occurred";
    }

    GatewayException exception = new GatewayException(message);
    exception.setStatusCode(statusCode);
    exception.setErrorResponse(response);

    throw exception;
}
 
Example 8
Source File: SfmtaApiCaller.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
	try {
		// Create the connection
		URL url = new URL(baseUrl);
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

		// Set parameters for the connection
		con.setRequestMethod("POST"); 
		con.setRequestProperty("content-type", "application/json");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches (false);
		
		// API now uses basic authentication
		String authString = login.getValue() + ":" + password.getValue();
		byte[] authEncBytes =
				Base64.encodeBase64(authString.getBytes());
		String authStringEnc = new String(authEncBytes);
		con.setRequestProperty("Authorization", "Basic "
				+ authStringEnc);

		// Set the timeout so don't wait forever (unless timeout is set to 0)
		int timeoutMsec = timeout.getValue();
		con.setConnectTimeout(timeoutMsec);
		con.setReadTimeout(timeoutMsec);

		// Write the json data to the connection
		DataOutputStream wr = new DataOutputStream(con.getOutputStream ());
		wr.writeBytes(jsonStr);
		wr.flush();
		wr.close();
		
		// Get the response
		int responseCode = con.getResponseCode();
		
		// If wasn't successful then log the response so can debug
		if (responseCode != 200) {			
			String responseStr = "";
			if (responseCode != 500) {
				// Response code indicates there was a problem so get the
				// reply in case API returned useful error message
				InputStream inputStream = con.getErrorStream();
				if (inputStream != null) {
					BufferedReader in =
							new BufferedReader(new InputStreamReader(
									inputStream));
					String inputLine;
					StringBuffer response = new StringBuffer();
					while ((inputLine = in.readLine()) != null) {
						response.append(inputLine);
					}
					in.close();
					responseStr = response.toString();
				}
			}

			// Lot that response code indicates there was a problem
			logger.error("Bad HTTP response {} when writing data to SFMTA "
					+ "API. Response text=\"{}\" URL={} json=\n{}",
					responseCode, responseStr, baseUrl, jsonStr);
		}

		// Done so disconnect just for the heck of it
		con.disconnect();
		
		// Return whether was successful
		return responseCode == 200;
	} catch (IOException e) {
		logger.error("Exception when writing data to SFMTA API: \"{}\" "
				+ "URL={} json=\n{}", 
				e.getMessage(), baseUrl, jsonStr);
		
		// Return that was unsuccessful
		return false;
	}
	
}