Code example for HttpsURLConnection

Methods: connect, getOutputStream, getResponseCode, getResponseMessage, setDoOutput, setRequestMethod, setRequestProperty, setSSLSocketFactory

0
 
  private String makeRequest(String urlFragment, String method, String body) throws IOException {
    HttpsURLConnection connection = getConnection(urlFragment, method);
 
    if (body != null) {
      connection.setDoOutput(true);
    } 
 
    connection.connect();
 
    if (body != null) {
      Log.w("GcmSocket", method +  "  --  " + body);
      OutputStream out = connection.getOutputStream();
      out.write(body.getBytes());
      out.close();
    } 
 
    if (connection.getResponseCode() != 200) {
      throw new IOException("Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
    } 
 
    return Util.readFully(connection.getInputStream());
  } 
 
  private HttpsURLConnection getConnection(String urlFragment, String method) throws IOException {
    try { 
      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, trustManagerFactory.getTrustManagers(), null);
 
      URL url = new URL(String.format("https://gcm.textsecure.whispersystems.org%s", urlFragment));
      HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
      connection.setSSLSocketFactory(context.getSocketFactory());
      connection.setRequestMethod(method);
      connection.setRequestProperty("Content-Type", "application/json");
 
      if (password != null) {
        System.out.println("Adding authorization header: " + getAuthorizationHeader());
        connection.setRequestProperty("Authorization", getAuthorizationHeader());
      }