Example usage for javax.net.ssl HttpsURLConnection getResponseCode

List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getResponseCode.

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:org.globusonline.transfer.JSONTransferAPIClient.java

public Result requestResult(String method, String path, JSONObject data, Map<String, String> queryParams)
        throws IOException, MalformedURLException, GeneralSecurityException, JSONException, APIError {
    String stringData = null;/*from www  .j a  v a 2  s. c om*/
    if (data != null)
        stringData = data.toString();

    HttpsURLConnection c = request(method, path, stringData, queryParams);

    Result result = new Result();
    result.statusCode = c.getResponseCode();
    result.statusMessage = c.getResponseMessage();

    result.document = new JSONObject(readString(c.getInputStream()));

    c.disconnect();

    return result;
}

From source file:org.schabi.newpipe.download.FileDownloader.java

/** AsyncTask impl: executed in background thread does the download */
@Override/*from   w w  w  .  ja va  2s. co m*/
protected Void doInBackground(Void... voids) {
    HttpsURLConnection con = null;
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        con = NetCipher.getHttpsURLConnection(fileURL);
        int responseCode = con.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            fileSize = con.getContentLength();
            inputStream = new BufferedInputStream(con.getInputStream());
            outputStream = new FileOutputStream(saveFilePath);

            int bufferSize = 8192;
            int downloaded = 0;

            int bytesRead = -1;
            byte[] buffer = new byte[bufferSize];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                downloaded += bytesRead;
                if (downloaded % 50000 < bufferSize) {
                    publishProgress(downloaded);
                }
            }

            publishProgress(bufferSize);

        } else {
            Log.i(TAG, "No file to download. Server replied HTTP code: " + responseCode);
        }
    } catch (IOException e) {
        Log.e(TAG, "No file to download. Server replied HTTP code: ", e);
        e.printStackTrace();
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (con != null) {
            con.disconnect();
        }
    }
    return null;
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;//  w  ww  .  ja va2 s. c  o m
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getItemsDataFromRiotAPI() throws IOException, ParseException {
    String line;/*from   w  ww.  ja v  a  2  s .  c o  m*/
    String result = "";
    URL url = new URL("https://global.api.pvp.net/api/lol/static-data/euw/v1.2/item?itemListData=tags&api_key="
            + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getItemsFromData(result);
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getChampionsDataFromRiotAPI() throws IOException, ParseException {
    String line;//  www.  ja v a  2s  .  c o  m
    String result = "";
    URL url = new URL(
            "https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getChampionsFromData(result);
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerIdDataFromRiotAPI(String region, String summonerName)
        throws MalformedURLException, IOException, ParseException {
    String line;//from w ww .  ja  v  a 2  s.  c o m
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/"
            + summonerName + "?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerDataFromRiotAPI(String region, Long summonerID)
        throws MalformedURLException, IOException {
    String line;//from   w  w w .j  a  va  2s . c o m
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/"
            + summonerID + "/entry?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

From source file:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java

public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException {

    request.request.technicalUser.username = this.user;
    request.request.technicalUser.password = this.password;

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, request);//from w  w  w.  j a v  a  2  s .  c o  m

    String requestJson = sw.getBuffer().toString();

    logger.debug("callWebService(): jsonRequest:" + requestJson);

    URL url = new URL(this.endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    out.write(requestJson.getBytes("UTF-8"));
    out.flush();
    int responseCode = conn.getResponseCode();

    InputStream input = conn.getInputStream();

    ByteArrayOutputStream data = new ByteArrayOutputStream();
    int len;
    byte[] buf = new byte[50000];
    while ((len = input.read(buf)) > 0) {
        data.write(buf, 0, len);
    }
    conn.disconnect();
    String jsonResponse = new String(data.toByteArray(), "UTF-8");

    if (responseCode != 200) {
        throw new IOException(jsonResponse);
    }

    logger.debug("callWebService(): jsonResponse:" + jsonResponse);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    T response = mapper.readValue(new StringReader(jsonResponse), clazz);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    sw = new StringWriter();
    mapper.writeValue(sw, response);
    logger.debug(
            "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString());

    return response;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse getRequest(String Uri, String requestParameters) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;/*from   w  ww.  j av  a2 s. co m*/
        if (requestParameters != null && requestParameters.length() > 0) {
            urlStr += "?" + requestParameters;
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.liberty.android.fantastischmemo.downloader.google.CellsFactory.java

public static void uploadCells(Spreadsheet spreadsheet, Worksheet worksheet, Cells cells, String authToken)
        throws IOException {
    URL url = new URL("https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full/batch?access_token=" + authToken);
    String urlPrefix = "https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full";

    for (int r = 0; r < cells.getRowCounts(); r += MAX_BATCH_SIZE) {
        int upBound = Math.min(r + MAX_BATCH_SIZE, cells.getRowCounts());

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);/*w  w w .j ava2  s  . com*/
        conn.setDoOutput(true);
        conn.addRequestProperty("Content-Type", "application/atom+xml");
        //conn.addRequestProperty("Content-Length", "" + payload.length());
        conn.addRequestProperty("If-Match", "*");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());

        StringBuilder head = new StringBuilder();
        head.append("<?xml version='1.0' encoding='UTF-8'?>");
        head.append(
                "<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:batch=\"http://schemas.google.com/gdata/batch\" xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">");
        head.append("<id>" + urlPrefix + "</id>");

        out.write(head.toString());

        for (int i = r; i < upBound; i++) {
            List<String> row = cells.getRow(i);
            for (int j = 0; j < row.size(); j++) {
                out.write(getEntryToRequesetString(urlPrefix, i + 1, j + 1, row.get(j)));
            }
        }
        out.write("</feed>");

        out.close();
        if (conn.getResponseCode() / 100 >= 3) {
            String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
            throw new IOException(s);
        }
    }
}