コード例 #1
0
ファイル: TlsCheck.java プロジェクト: VNeufeld/testGis
  /**
   * Tests whether this client can make an HTTP connection with TLS 1.2.
   *
   * @return true if connection is successful. false otherwise.
   */
  public static boolean testTls12Connection() {
    String protocol = "N/A";
    try {
      SSLContext sslContext = SSLContext.getInstance(getLatestProtocol().toString());
      protocol = sslContext.getProtocol();
      sslContext.init(null, null, null);
      HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

      URL url = new URL("https://" + ENDPOINT);
      HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();

      httpsConnection.connect();
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
      StringBuilder body = new StringBuilder();
      while (reader.ready()) {
        body.append(reader.readLine());
      }
      httpsConnection.disconnect();
      if (body.toString().equals("PayPal_Connection_OK")) {
        return true;
      }

    } catch (NoSuchAlgorithmException e) {
    } catch (UnknownHostException e) {
    } catch (IOException e) {
    } catch (KeyManagementException e) {
    }
    return false;
  }
コード例 #2
0
 /**
  * HttpUrlConnection支持所有Https免验证,不建议使用
  *
  * @throws KeyManagementException
  * @throws NoSuchAlgorithmException
  * @throws IOException
  */
 public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException {
   URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version");
   SSLContext context = SSLContext.getInstance("TLS");
   context.init(null, new TrustManager[] {new TrustAllManager()}, null);
   HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
   HttpsURLConnection.setDefaultHostnameVerifier(
       new HostnameVerifier() {
         @Override
         public boolean verify(String arg0, SSLSession arg1) {
           return true;
         }
       });
   HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
   connection.setDoInput(true);
   connection.setDoOutput(false);
   connection.setRequestMethod("GET");
   connection.connect();
   InputStream in = connection.getInputStream();
   BufferedReader reader = new BufferedReader(new InputStreamReader(in));
   String line = "";
   StringBuffer result = new StringBuffer();
   while ((line = reader.readLine()) != null) {
     result.append(line);
   }
   String reString = result.toString();
   Log.i("TTTT", reString);
 }
コード例 #3
0
  /**
   * Synchronous call for logging in
   *
   * @param httpBody
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws JSONException
   */
  public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    HttpsURLConnection connection = createSecureConnection(url);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
      LoggingUtils.d(LOG_TAG, connection.toString());
      response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
      LoggingUtils.e(
          LOG_TAG,
          "Error reading stream \""
              + connection.getInputStream()
              + "\". "
              + e.getLocalizedMessage(),
          null);
    } catch (IOException e) {
      response = readFromStream(connection.getErrorStream());
    } finally {
      connection.disconnect();
    }

    return response;
  }
コード例 #4
0
  @Override
  protected HttpURLConnection openConnection(String path, String query) throws IOException {
    query = addDelegationTokenParam(query);
    final URL url = new URL("https", nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    // bypass hostname verification
    try {
      conn.setHostnameVerifier(new DummyHostnameVerifier());
      conn.setRequestMethod("GET");
      conn.connect();
    } catch (IOException ioe) {
      throwIOExceptionFromConnection(conn, ioe);
    }

    // check cert expiration date
    final int warnDays = ExpWarnDays;
    if (warnDays > 0) { // make sure only check once
      ExpWarnDays = 0;
      long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY + System.currentTimeMillis();
      X509Certificate[] clientCerts = (X509Certificate[]) conn.getLocalCertificates();
      if (clientCerts != null) {
        for (X509Certificate cert : clientCerts) {
          long expTime = cert.getNotAfter().getTime();
          if (expTime < expTimeThreshold) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n Client certificate " + cert.getSubjectX500Principal().getName());
            int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY);
            sb.append(" have " + dayOffSet + " days to expire");
            LOG.warn(sb.toString());
          }
        }
      }
    }
    return (HttpURLConnection) conn;
  }
コード例 #5
0
ファイル: KeyspotLoader.java プロジェクト: Zichsah/frpapp
 /**
  * Connects to the web site and parses the information into enties.
  *
  * @return A List of Entries.
  */
 public List<Entry> reload(String zip) {
   entries = null;
   parser = new XmlParser();
   try {
     url = new URL("https://www.phillykeyspots.org/keyspot-mobile-map.xml/" + zip + "_2");
     HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
     conn.setReadTimeout(10000 /*milliseconds*/);
     conn.setConnectTimeout(15000 /*milliseconds*/);
     conn.setRequestMethod("GET");
     conn.setDoInput(true);
     conn.connect();
     stream = conn.getInputStream();
     entries = parser.parse(stream);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (stream != null) {
       try {
         stream.close();
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
   return entries;
 }
コード例 #6
0
 @Override
 public String receiveData(String urlPath, String streamData) {
   StringBuilder responseStringBuilder = new StringBuilder();
   URL url = null;
   URLConnection urlConnection = null;
   Scanner scanner = null;
   try {
     url = new URL(urlPath);
     urlConnection = url.openConnection();
     HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) urlConnection;
     httpsUrlConnection.setDoOutput(true);
     httpsUrlConnection.setDoInput(true);
     httpsUrlConnection.setUseCaches(false);
     httpsUrlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
     httpsUrlConnection.setRequestMethod("POST");
     httpsUrlConnection.connect();
     if (streamData != null) {
       OutputStream outputStream = httpsUrlConnection.getOutputStream();
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
       outputStreamWriter.write(streamData);
       outputStreamWriter.flush();
       outputStreamWriter.close();
     }
     scanner = new Scanner(urlConnection.getInputStream(), "UTF-8");
     while (scanner.hasNext()) {
       String tempString = scanner.nextLine().trim();
       responseStringBuilder.append(tempString);
     }
     scanner.close();
   } catch (Exception e) {
     return null;
   }
   return responseStringBuilder.toString();
 }
コード例 #7
0
ファイル: H5Util.java プロジェクト: yikangmc/yikangPortal
 /**
  * 方法名:httpRequest</br> 详述:发送http请求</br> 开发人员:souvc </br> 创建时间:2016-1-5 </br>
  *
  * @param requestUrl
  * @param requestMethod
  * @param outputStr
  * @return 说明返回值含义
  * @throws 说明发生此异常的条件
  */
 private static JsonNode httpRequest(String requestUrl, String requestMethod, String outputStr) {
   StringBuffer buffer = new StringBuffer();
   JsonNode josnNode = null;
   JSONObject jsonObject = null;
   try {
     URL url = new URL(requestUrl);
     HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
     httpUrlConn.setRequestMethod("GET");
     httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     httpUrlConn.setDoOutput(true);
     httpUrlConn.setDoInput(true);
     httpUrlConn.setUseCaches(false);
     System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // 连接超时30秒
     System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
     httpUrlConn.connect();
     InputStream inputStream = httpUrlConn.getInputStream();
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
     BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
     String str = null;
     while ((str = bufferedReader.readLine()) != null) {
       buffer.append(str);
     }
     josnNode = new ObjectMapper().readTree(buffer.toString());
     bufferedReader.close();
     inputStreamReader.close();
     inputStream.close();
     inputStream = null;
     httpUrlConn.disconnect();
   } catch (ConnectException ce) {
     ce.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return josnNode;
 }
コード例 #8
0
  protected Void doInBackground(Integer... params) {
    Integer genreId = params[0];
    final String BASE_URL = "https://api.themoviedb.org/3/";
    final String MOVIES_OF_GENRE_LIST_METHOD = "genre/" + genreId + "/movies";
    final String API_KEY_PARAM = "api_key";
    final String API_KEY_VALUE = "21ac243915da272c3c6b92a9958a3650";
    //        final String REQUEST_TOKEN_PARAM = "request_token";
    //        final String SESSION_ID_PARAM = "session_id";
    //        final String USER_NAME_PARAM = "username";
    //        final String PASSWORD_PARAM = "password";

    BufferedReader reader = null;
    HttpsURLConnection urlConnection = null;
    String moviesListJson = null;
    Uri builtUri =
        Uri.parse(BASE_URL + MOVIES_OF_GENRE_LIST_METHOD)
            .buildUpon()
            .appendQueryParameter(API_KEY_PARAM, API_KEY_VALUE)
            .build();
    try {
      URL url = new URL(builtUri.toString());
      urlConnection = (HttpsURLConnection) url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setRequestProperty("Accept", "application/json");
      urlConnection.connect();

      InputStream inputStream = urlConnection.getInputStream();
      StringBuffer buffer = new StringBuffer();
      if (inputStream == null) {
        Log.e(LOG_TAG, "INPUT STREAM from http request returned nothing");
        return null;
      }
      reader = new BufferedReader(new InputStreamReader(inputStream));
      String ln;
      while ((ln = reader.readLine()) != null) {
        buffer.append(ln + "\n");
      }
      if (buffer.length() == 0) {
        Log.e(LOG_TAG, "empty buffer from http request, no data found");
        return null;
      }
      moviesListJson = buffer.toString();
    } catch (IOException e) {
      Log.e(LOG_TAG, "Error ", e);
      return null;
    }
    try {
      JSONObject moviesListObject = new JSONObject(moviesListJson);
      int page = moviesListObject.getInt("page");
      int pages = moviesListObject.getInt("total_pages");
      JSONArray results = moviesListObject.getJSONArray("results");
      mMovies = Movie.fromJson(results);
    } catch (JSONException e) {
      Log.e(LOG_TAG, "Error: ", e);
      return null;
    }
    return null;
  }
コード例 #9
0
  public static String httsRequest(String url, String contentdata) {
    String str_return = "";
    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {

      e.printStackTrace();
    }
    try {
      sc.init(
          null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom());
    } catch (KeyManagementException e) {

      e.printStackTrace();
    }
    URL console = null;
    try {
      console = new URL(url);
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    HttpsURLConnection conn;
    try {
      conn = (HttpsURLConnection) console.openConnection();
      conn.setRequestMethod("POST");
      conn.setSSLSocketFactory(sc.getSocketFactory());
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      conn.setRequestProperty("Accept", "application/json");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json"
      String inpputs = contentdata;
      OutputStream os = conn.getOutputStream();
      os.write(inpputs.getBytes());
      os.close();
      conn.connect();
      InputStream is = conn.getInputStream();
      // // DataInputStream indata = new DataInputStream(is);
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String ret = "";
      while (ret != null) {
        ret = reader.readLine();
        if (ret != null && !ret.trim().equals("")) {
          str_return = str_return + ret;
        }
      }
      is.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return str_return;
  }
コード例 #10
0
    private String downloadUrl(String urlString)
        throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException,
            CertificateException {

      HostnameVerifier hostnameVerifier =
          new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
              HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
              return hv.verify("localhost", session);
            }
          };
      URL url = new URL(urlString);
      HttpsURLConnection conn = null;
      // Get an instance of the Bouncy Castle KeyStore format
      KeyStore trusted = KeyStore.getInstance("BKS");
      // Get the raw resource, which contains the keystore with
      // your trusted certificates (root and any intermediate certs)
      InputStream in =
          activity.getApplicationContext().getResources().openRawResource(R.raw.mykeystore);
      try {
        // Initialize the keystore with the provided trusted
        // certificates
        // Also provide the password of the keystore
        trusted.load(in, "my_password".toCharArray());
      } finally {
        in.close();
      }
      String algorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
      tmf.init(trusted);

      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);

      conn = (HttpsURLConnection) url.openConnection();
      conn.setHostnameVerifier(hostnameVerifier);
      conn.setSSLSocketFactory(context.getSocketFactory());
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      conn.setRequestProperty("Accept", "text/xml");
      conn.setRequestProperty(
          "Authorization",
          "Basic "
              + Base64.encodeToString(
                  ((this.userName + ":" + this.passWord).getBytes()), Base64.NO_WRAP));
      // Starts the query
      conn.connect();
      return conn.getResponseMessage();
    }
コード例 #11
0
  private Bitmap getBitmap(String imagemUrl) {
    Bitmap bitmap = null;
    try {
      HttpsURLConnection connection = (HttpsURLConnection) new URL(imagemUrl).openConnection();
      connection.setDoInput(true);
      connection.connect();
      InputStream input = connection.getInputStream();
      bitmap = BitmapFactory.decodeStream(input);
      input.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return bitmap;
  }
コード例 #12
0
 private void GetHttps() {
   String https = "https://mail.qq.com/cgi-bin/loginpage";
   try {
     HttpsURLConnection conn = (HttpsURLConnection) new URL(https).openConnection();
     conn.setDoOutput(true);
     conn.setDoInput(true);
     conn.connect();
     BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     StringBuffer sb = new StringBuffer();
     String line;
     while ((line = br.readLine()) != null) sb.append(line);
     Log.e("testcaseLog", sb.toString());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #13
0
ファイル: TokenTicket.java プロジェクト: rinoux/service
  /**
   * 模拟http请求
   *
   * @param requestUrl URL
   * @return
   */
  private static JSONObject httpRequest(String requestUrl) {
    // TODO Auto-generated method stub
    JSONObject jsonObject = null;
    String requestMethod = "GET";
    StringBuffer buffer = new StringBuffer();
    try {

      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new java.security.SecureRandom());

      SSLSocketFactory ssf = sslContext.getSocketFactory();

      URL url = new URL(requestUrl);
      HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
      httpUrlConn.setSSLSocketFactory(ssf);

      httpUrlConn.setDoOutput(true);
      httpUrlConn.setDoInput(true);
      httpUrlConn.setUseCaches(false);

      httpUrlConn.setRequestMethod(requestMethod);

      if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();

      InputStream inputStream = httpUrlConn.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

      String str = null;
      while ((str = bufferedReader.readLine()) != null) {
        buffer.append(str);
      }
      bufferedReader.close();
      inputStreamReader.close();

      inputStream.close();
      inputStream = null;
      httpUrlConn.disconnect();
      jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (ConnectException ce) {
      log.error("http请求数据失败�?" + ce.getMessage());
    } catch (Exception e) {
      log.error("http请求数据失败�?" + e.getMessage());
    }
    return jsonObject;
  }
コード例 #14
0
  private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
      throws IOException {

    HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection();
    nection.setDoInput(true);
    nection.setDoOutput(true);
    nection.setRequestProperty("Content-Type", "application/json");
    nection.setRequestProperty("Accept", "application/json");
    nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME);
    if (accessToken != null) {
      nection.setRequestProperty("Authorization", "token " + accessToken);
    }

    OutputStream os = nection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(params.toString());
    writer.flush();
    writer.close();
    os.close();

    try {

      nection.connect();
      InputStream in = new BufferedInputStream(nection.getInputStream());
      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      StringBuilder response = new StringBuilder();
      while (true) {
        String line = reader.readLine();
        if (line == null) {
          break;
        }
        response.append(line);
      }

      try {
        return new JSONObject(response.toString());
      } catch (JSONException e) {
        throw new IOException(e);
      }

    } finally {
      nection.disconnect();
    }
  }
コード例 #15
0
  protected static String httpsPostImplement(String serviceURL, String postData)
      throws IOException {

    String dataBuff = "";

    URL postURL = new URL(serviceURL);
    HttpsURLConnection connection = (HttpsURLConnection) postURL.openConnection();
    connection.setRequestProperty("Accept-Language", "zh-tw,en-us;q=0.7,en;q=0.3");
    connection.connect();

    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    writer.writeBytes(postData);

    String lines;
    while ((lines = reader.readLine()) != null) {
      dataBuff = dataBuff + lines;
    }
    reader.close();

    connection.disconnect();
    return dataBuff;
  }
コード例 #16
0
  private void GetHttps() {
    String https = "https://trade3.guosen.com.cn/mtrade/check_version";
    try {
      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, new TrustManager[] {new MyTrustManager()}, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
      HttpsURLConnection conn = (HttpsURLConnection) new URL(https).openConnection();
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.connect();

      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      StringBuffer sb = new StringBuffer();
      String line;
      while ((line = br.readLine()) != null) sb.append(line);

      textView.setText(sb.toString());

    } catch (Exception e) {
      // Log.e("SSL", e.getMessage());
    }
  }
コード例 #17
0
    public String getData(String urlPath) {
      try {
        URL url = new URL(urlPath);

        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        //    	   urlConnection.setSSLSocketFactory(getSocketFactory());
        urlConnection.connect();
        java.io.InputStream input = urlConnection.getInputStream();

        int count;

        //            java.io.InputStream input = conection.getInputStream();
        // getting file length
        int lenghtOfFile = urlConnection.getContentLength();
        // input stream to read file - with 8k buffer
        //			  java.io.InputStream input = new BufferedInputStream(urlConnection.openStream());
        // Output stream to write file
        byte data[] = new byte[4096];
        long total = 0;
        StringBuilder sb = new StringBuilder();
        while ((count = input.read(data)) != -1) {

          //            while (input.read(b) > 0) {

          sb.append(new String(data, Charset.forName("utf-8")));
        }

        input.close();

        return sb.toString();
      } catch (Throwable e) {
        e.printStackTrace();
        Log.d("MoreScreen", "Error throwing in version fetching from play store." + e.toString());
      }
      return null;
    }
コード例 #18
0
ファイル: JavaHttpUtility.java プロジェクト: pureyou/Beebo
  public String doPost(String urlAddress, Map<String, String> param) throws WeiboException {
    BeeboApplication globalContext = BeeboApplication.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
      URL url = new URL(urlAddress);
      Proxy proxy = getProxy();
      HttpsURLConnection uRLConnection;
      if (proxy != null) {
        uRLConnection = (HttpsURLConnection) url.openConnection(proxy);
      } else {
        uRLConnection = (HttpsURLConnection) url.openConnection();
      }

      uRLConnection.setDoInput(true);
      uRLConnection.setDoOutput(true);
      uRLConnection.setRequestMethod("POST");
      uRLConnection.setUseCaches(false);
      uRLConnection.setConnectTimeout(CONNECT_TIMEOUT);
      uRLConnection.setReadTimeout(READ_TIMEOUT);
      uRLConnection.setInstanceFollowRedirects(false);
      uRLConnection.setRequestProperty("Connection", "Keep-Alive");
      uRLConnection.setRequestProperty("Charset", "UTF-8");
      uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
      uRLConnection.connect();

      DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
      out.write(Utility.encodeUrl(param).getBytes());
      out.flush();
      out.close();
      return handleResponse(uRLConnection);
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    }
  }
コード例 #19
0
ファイル: HttpUtil.java プロジェクト: rranz/javalego
  /**
   * Realiza una peticción https GET utilizando el proxy especificado (con certificado)
   *
   * @param sUrl Dirección http a resolver
   * @param sProxy Nombre del proxy, p.e. proxy.bde.es
   * @param sProxyPort Puerto del proxy, p.e. 80
   * @return String con el texto devuelto
   * @throws MalformedURLException
   * @throws IOException
   */
  public static String httpsGetCertificado(
      String sUrl,
      String sProxy,
      String sProxyPort,
      int timeoutMs,
      String alias,
      String keyStore,
      String trustStore,
      String keyStorePassword,
      String trustStorePassword,
      String pCookies,
      int numeroDeRedireccionActual)
      throws MalformedURLException, IOException {

    try {
      SSLSocketFactory sc =
          new SSLSocketFactoryGenerator(
                  alias, keyStore, trustStore, keyStorePassword, trustStorePassword)
              .getSSLSocketFactory();
      HttpsURLConnection.setDefaultSSLSocketFactory(sc);

    } catch (Exception e) {

      return null;
    }

    HttpsURLConnection con = null;
    URL url = new URL(sUrl);

    // Creamos la conexión con la url
    if (sProxy != null && sProxyPort != null) {
      Proxy proxy =
          new Proxy(Proxy.Type.HTTP, new InetSocketAddress(sProxy, Integer.parseInt(sProxyPort)));

      con = (HttpsURLConnection) url.openConnection(proxy);
    } else {
      con = (HttpsURLConnection) url.openConnection();
    }

    // Evitamos que se sigan los redirects ya que los redirects los hace sin
    // pasar las cookies lo cual es un bug.
    con.setInstanceFollowRedirects(false);
    // Evitamos el uso de respuestas cacheadas
    con.setUseCaches(false);

    // Fijamos los timeouts
    if (timeoutMs > 0) {
      con.setConnectTimeout(timeoutMs);
      con.setReadTimeout(timeoutMs);
    }
    // Respuesta de la petición
    con.connect();

    InputStream in = con.getInputStream();
    StringBuffer sb = new StringBuffer();

    int c;
    while ((c = in.read()) != -1) sb.append((char) c);
    int responseCode = con.getResponseCode();
    String cookies = HttpUtil.getResponseHeader((URLConnection) con, "Set-Cookie");
    if (!StringUtils.isEmpty(pCookies) && !StringUtils.isEmpty(cookies)) {
      cookies = pCookies + "; " + cookies;
    }
    String location = HttpUtil.getResponseHeaderLocation(sUrl, (URLConnection) con);
    con.disconnect();

    // Comprobación de si es una redirección
    if (responseCode == 301 || responseCode == 302) {
      if (numeroDeRedireccionActual < 10) {
        return httpsGetCertificado(
            location,
            sProxy,
            sProxyPort,
            timeoutMs,
            alias,
            keyStore,
            trustStore,
            keyStorePassword,
            trustStorePassword,
            cookies,
            numeroDeRedireccionActual + 1);
      } else {
        throw new IOException(
            "Se han producido 10 redirecciones consecutivas al solicitar la página web. Se cancela la petición");
      }
    } else {
      return sb.toString();
    }
  }
コード例 #20
0
ファイル: HttpUtil.java プロジェクト: rranz/javalego
  /**
   * Realiza una peticción https GET utilizando el proxy especificado
   *
   * @param sUrl Dirección http a resolver
   * @param sProxy Nombre del proxy, p.e. proxy.bde.es
   * @param sProxyPort Puerto del proxy, p.e. 80
   * @return String con el texto devuelto
   * @throws MalformedURLException
   * @throws IOException
   */
  public static String httpsGet(
      String sUrl,
      String sProxy,
      String sProxyPort,
      int timeoutMs,
      String pCookies,
      int numeroDeRedireccionActual)
      throws MalformedURLException, IOException {

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            @Override
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}

            @Override
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}
          }
        };

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {

      return null;
    }

    HttpsURLConnection con = null;
    URL url = new URL(sUrl);

    // Creamos la conexión con la url
    if (sProxy != null && sProxyPort != null) {
      Proxy proxy =
          new Proxy(Proxy.Type.HTTP, new InetSocketAddress(sProxy, Integer.parseInt(sProxyPort)));

      con = (HttpsURLConnection) url.openConnection(proxy);
    } else {
      con = (HttpsURLConnection) url.openConnection();
    }

    // Evitamos que se sigan los redirects ya que los redirects los hace sin
    // pasar las cookies lo cual es un bug.
    con.setInstanceFollowRedirects(false);
    // Evitamos el uso de respuestas cacheadas
    con.setUseCaches(false);

    // Fijamos los timeouts
    if (timeoutMs > 0) {
      con.setConnectTimeout(timeoutMs);
      con.setReadTimeout(timeoutMs);
    }

    // Enviamos las cookies
    if (!StringUtils.isEmpty(pCookies)) {
      con.setRequestProperty("Cookie", pCookies);
    }

    // Respuesta de la petición
    con.connect();

    InputStream in = con.getInputStream();
    StringBuffer sb = new StringBuffer();

    int c;
    while ((c = in.read()) != -1) sb.append((char) c);

    int responseCode = con.getResponseCode();
    String cookies = HttpUtil.getResponseHeader((URLConnection) con, "Set-Cookie");
    if (!StringUtils.isEmpty(pCookies) && !StringUtils.isEmpty(cookies)) {
      cookies = pCookies + "; " + cookies;
    }
    String location = HttpUtil.getResponseHeaderLocation(sUrl, (URLConnection) con);
    con.disconnect();

    // Comprobación de si es una redirección
    if (responseCode == 301 || responseCode == 302) {
      if (numeroDeRedireccionActual < 10) {
        Logger.getRootLogger().debug("Redirigiendo a " + location);
        Logger.getRootLogger().debug("Cookies enviadas:" + cookies);
        return httpsGet(
            location, sProxy, sProxyPort, timeoutMs, cookies, numeroDeRedireccionActual);
      } else {
        throw new IOException(
            "Se han producido 10 redirecciones consecutivas al solicitar la página web. Se cancela la petición");
      }
    } else {
      return sb.toString();
    }
  }
コード例 #21
0
  // gets VM home and data page based on boolean parameter
  public static String fetchURL(String username, String password, Boolean getData) {
    String line = "";

    String url = "https://www2.virginmobileusa.com/login/login.do";
    String dataUrl = "https://www2.virginmobileusa.com/myaccount/dataPlanHistory.do";
    try {
      TrustManager[] trustAllCerts =
          new TrustManager[] {
            new X509TrustManager() {
              public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
              }

              public void checkClientTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}

              public void checkServerTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}
            }
          };
      try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      } catch (Exception e) {
        e.getMessage();
      }

      HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
      ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());

      connection.setDoOutput(true);

      String content = "loginRoutingInfo=&min=" + username + "&vkey=" + password + "&submit=submit";

      connection.setFixedLengthStreamingMode(content.length());
      connection.setRequestProperty("Host", "www2.virginmobileusa.com");
      connection.setRequestProperty("Accept-Language", "en-US,en;q=0.9");

      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
      out.write(content);
      out.close();

      InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());

      BufferedReader buff = new BufferedReader(in);

      StringBuilder sb = new StringBuilder();

      while ((line = buff.readLine()) != null) {
        sb.append(line);
      }

      // telephone
      int tel_infoStartIndex = sb.indexOf("id=\"headerimage\"");
      int tel_infoEndIndex = sb.indexOf("<ul class=\"tabnav\">");
      // balance info
      int balance_infoStartIndex = sb.indexOf("id=\"balance_info2b\">");
      int balance_infoEndIndex = sb.indexOf("id=\"payment_strip\"");
      // account activity
      int account_activityStartIndex = sb.indexOf("id=\"account_activity\"");
      int account_activityEndIndex = sb.indexOf("id=\"for_your_phone\"");

      // int mainContentIndex = sb.indexOf("id=\"mainContent\"");
      if (tel_infoStartIndex == -1) {
        line = "";
      } else {
        line = sb.substring(tel_infoStartIndex, tel_infoEndIndex);
      }
      if (balance_infoStartIndex != -1) {

        line += sb.substring(balance_infoStartIndex, balance_infoEndIndex);
      }
      if (account_activityStartIndex != -1) {
        line += sb.substring(account_activityStartIndex, account_activityEndIndex);
      }
      // Now, try to grab data usage
      String cookies = "";
      // 1. Grab and store cookies
      String headerName = null;
      for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equalsIgnoreCase("Set-Cookie")) {
          String cookie = connection.getHeaderField(i);
          cookie = cookie.substring(0, cookie.indexOf(";"));
          String cookieName = cookie.substring(0, cookie.indexOf("="));
          String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
          cookies = cookies + cookieName + "=" + cookieValue + "; ";
        }
      }
      if (getData == true) {
        // get data page
        HttpsURLConnection connection2 = (HttpsURLConnection) new URL(dataUrl).openConnection();
        ((HttpsURLConnection) connection2).setHostnameVerifier(new AllowAllHostnameVerifier());

        connection2.setDoOutput(true);
        connection2.setRequestProperty("Cookie", cookies);
        connection2.connect();
        InputStreamReader in2 = new InputStreamReader((InputStream) connection2.getContent());

        BufferedReader buff2 = new BufferedReader(in2);

        StringBuilder sb2 = new StringBuilder();

        String dataPage;
        while ((dataPage = buff2.readLine()) != null) {
          sb2.append(dataPage);
        }

        int dataContentIndex = sb2.indexOf("<h2>Mobile Web History</h2>");
        if (dataContentIndex == -1) {
          dataPage = "";
        } else {
          dataPage = sb2.substring(dataContentIndex);
          line += ("****************" + dataPage);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      // System.err.println("exception 83");
      // System.err.println(e.getMessage());
      // System.err.println(line);
      return line;
      // rc.put("isValid", "FALSE");
    }
    return line;
  }
コード例 #22
0
ファイル: XrayCheckTask.java プロジェクト: duo-labs/xray
  @Override
  protected XrayUpdater.CheckResult doInBackground(Void... v) {
    HttpsURLConnection urlConnection = null;
    InputStream inputStream = null;
    XrayUpdater.CheckResult result = XrayUpdater.CheckResult.UP_TO_DATE;

    Log.d(TAG, "Attempting to fetch manifest...");

    try {
      // issue a GET request to determine the latest available apk version
      URL url = new URL(XrayUpdater.VERSION_URL);
      urlConnection =
          PinningHelper.getPinnedHttpsURLConnection(context, XrayUpdater.CERT_PINS, url);
      urlConnection.setConnectTimeout(XrayUpdater.CONNECTION_TIMEOUT);
      urlConnection.setReadTimeout(XrayUpdater.READ_TIMEOUT);
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoInput(true);
      urlConnection.connect();

      int responseCode = urlConnection.getResponseCode();
      int apkVersion = -1;
      String apkName = null;
      String apkChecksum = null;

      // read the results into a byte array stream
      inputStream = new BufferedInputStream(urlConnection.getInputStream());
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

      if (responseCode != HttpURLConnection.HTTP_OK) {
        Log.d(TAG, "Error fetching app version, HTTP request returned: " + responseCode);
      } else if (!XrayUpdater.writeToOutputStream(inputStream, byteStream)) {
        Log.d(TAG, "Error fetching app version, invalid input stream");
      } else {
        // request looks okay, let's verify response signature
        Signature ecdsaSignature =
            Signature.getInstance(XrayUpdater.ECDSA_ALGORITHM, XrayUpdater.ECDSA_PROVIDER);
        PublicKey extPubKey = crypto.readPublicKey(XrayUpdater.SERVER_PUB_KEY);
        ecdsaSignature.initVerify(extPubKey);
        ecdsaSignature.update(byteStream.toByteArray());

        String signature = urlConnection.getHeaderField("Xray-Signature");
        byte[] signature_bytes = crypto.base64Decode(signature);

        if (!ecdsaSignature.verify(signature_bytes)) {
          Log.d(TAG, "Invalid signature");
        } else {
          Log.d(TAG, "Signature valid. Reading JSON response...");

          // signature is valid, so read version and filename from JSON response
          inputStream = new ByteArrayInputStream(byteStream.toByteArray());
          JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
          reader.beginObject();
          while (reader.hasNext()) {
            String key = reader.nextName();
            if (key.equals("apkVersion")) {
              apkVersion = Integer.parseInt(reader.nextString());
            } else if (key.equals("apkName")) {
              apkName = reader.nextString();
            } else if (key.equals("apkChecksum")) {
              apkChecksum = reader.nextString();
            } else {
              reader.skipValue();
            }
          }
          reader.endObject();
        }
      }

      if (apkVersion < 0 || apkName == null || apkChecksum == null) {
        Log.d(TAG, "Error fetching app version, JSON response missing fields");
      } else if (apkVersion == BuildConfig.VERSION_CODE) {
        Log.d(TAG, "Already up to date");
      } else { // out of date
        XrayUpdater.setSharedPreference("apkName", apkName);
        XrayUpdater.setSharedPreference("apkChecksum", apkChecksum);
        result = XrayUpdater.CheckResult.OUT_OF_DATE;
      }
    } catch (MalformedURLException e) {
      Log.d(TAG, "Found malformed URL when trying to update");
    } catch (SocketTimeoutException e) {
      Log.d(TAG, "Socket timed out when trying to update: " + e.toString());
    } catch (SSLHandshakeException e) {
      Log.d(TAG, "Failed SSL Handshake when trying to update: " + e.toString());
      result = XrayUpdater.CheckResult.SSL_ERROR;
    } catch (IOException e) {
      Log.d(TAG, "Found IO exception when trying to update: " + e.toString());
    } catch (Exception e) {
      Log.d(TAG, "Received error when trying to update: " + e.toString());
    } finally {
      Log.d(TAG, "Cleaning up check task...");

      // close the GET connection
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          Log.d(TAG, "Found IO exception when trying to close inputstream: " + e.toString());
        }
      }
      if (urlConnection != null) {
        urlConnection.disconnect();
      }

      Log.d(TAG, "Exiting check task");
    }
    return result;
  }
コード例 #23
0
  @SuppressWarnings("UseSpecificCatch")
  private static JSONObject readJsonFromUrl(String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;
    HttpsURLConnection urlConn;
    String jsonText = "";

    try {
      urlRaw = new URL(urlAddress);
      urlConn = (HttpsURLConnection) urlRaw.openConnection();
      urlConn.setDoInput(true);
      urlConn.setRequestMethod("GET");
      urlConn.addRequestProperty("Content-Type", "application/json");
      urlConn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
              + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
      urlConn.connect();

      if (urlConn.getResponseCode() == 200) {
        inputStream = urlConn.getInputStream();
      } else {
        inputStream = urlConn.getErrorStream();
      }

      BufferedReader rd =
          new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
      jsonText = readAll(rd);
      jsonResult = new JSONObject(jsonText);
      fillJSONObject(
          jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (NullPointerException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (SocketTimeoutException ex) {
      fillJSONObject(
          jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (IOException ex) {
      fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } catch (Exception ex) {
      fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
      com.gmt2001.Console.err.printStackTrace(ex);
    } finally {
      if (inputStream != null)
        try {
          inputStream.close();
        } catch (IOException ex) {
          fillJSONObject(
              jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
          com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

    return (jsonResult);
  }
コード例 #24
0
  /**
   * Synchronous call for logging out
   *
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws JSONException
   */
  public static String getLogoutResponse(Context context)
      throws MalformedURLException, IOException, JSONException {
    // Refresh if necessary
    if (WebServiceAuthProvider.tokenExpiredHint(context)) {
      WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
      // If we have refreshed max number of times, we will not do so again
      if (refreshed == 1) {
        refreshLimitReached = true;
      }

      URL url = new URL(urlForLogout(context));
      HttpsURLConnection connection = createSecureConnection(url);
      String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");

      connection.setRequestMethod("POST");
      connection.setRequestProperty("Authorization", authValue);
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.connect();

      try {
        LoggingUtils.d(LOG_TAG, "LogoutResponse" + connection.toString());
        response = readFromStream(connection.getInputStream());
      } catch (MalformedURLException e) {
        LoggingUtils.e(
            LOG_TAG,
            "Error reading stream \""
                + connection.getInputStream()
                + "\". "
                + e.getLocalizedMessage(),
            null);
      } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
      } finally {
        connection.disconnect();
      }

      // Allow for calls to return nothing
      if (response.length() == 0) {
        return "";
      }

      // Check for JSON parsing errors (will throw JSONException is can't be parsed)
      JSONObject object = new JSONObject(response);

      // If no error, return response
      if (!object.has("error")) {
        return response;
      }
      // If there is a refresh token error, refresh the token
      else if (object.getString("error").equals("invalid_token")) {
        if (refreshLimitReached) {
          // Give up
          return response;
        } else {
          // Refresh the token
          WebServiceAuthProvider.refreshAccessToken(context);
          refreshed++;
        }
      }
    } // while(!refreshLimitReached)

    return response;
  }
コード例 #25
0
  /**
   * Synchronous call to get a new client credentials token, required for creating new account
   *
   * @param url
   * @param clientCredentialsToken
   * @param httpMethod
   * @param httpBody
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws ProtocolException
   * @throws JSONException
   */
  public static String getClientCredentialsResponse(
      Context context,
      String url,
      String clientCredentialsToken,
      String httpMethod,
      Bundle httpBody)
      throws MalformedURLException, IOException, ProtocolException, JSONException {
    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
      // If we have refreshed max number of times, we will not do so again
      if (refreshed == 1) {
        refreshLimitReached = true;
      }

      HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url)));
      connection.setRequestMethod(httpMethod);
      connection.setDoOutput(true);
      connection.setDoInput(true);
      String authValue = "Bearer " + clientCredentialsToken;
      connection.setRequestProperty("Authorization", authValue);
      connection.connect();

      if (!httpBody.isEmpty()) {
        OutputStream os = new BufferedOutputStream(connection.getOutputStream());
        os.write(encodePostBody(httpBody).getBytes());
        os.flush();
      }

      try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
      } catch (FileNotFoundException e) {
        response = readFromStream(connection.getErrorStream());
      } finally {
        connection.disconnect();
      }

      // Allow for calls to return nothing
      if (response.length() == 0) {
        return "";
      }

      // Check for JSON parsing errors (will throw JSONException is can't be parsed)
      JSONObject object = new JSONObject(response);

      // If no error, return response
      if (!object.has("error")) {
        return response;
      }
      // If there is a refresh token error, refresh the token
      else if (object.getString("error").equals("invalid_token")) {
        if (refreshLimitReached) {
          // Give up
          return response;
        } else {
          // Refresh the token
          WebServiceAuthProvider.refreshAccessToken(context);
          refreshed++;
        }
      }
    } // while(!refreshLimitReached)

    return response;
  }
コード例 #26
0
ファイル: VingdClient.java プロジェクト: vingd/vingd-api-java
  @SuppressWarnings("unchecked")
  public Object request(String method, String resource, Object parameters)
      throws VingdTransportException, VingdOperationException, IOException {
    URL url = new URL(backendURL + resource);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    method = method.toUpperCase();
    if (method.equals("GET") || method.equals("POST") || method.equals("PUT")) {
      conn.setRequestMethod(method);
    } else {
      throw new VingdTransportException("Unsupported HTTP method.", "Request");
    }

    byte[] credBytes = (username + ":" + pwhash).getBytes("ASCII");
    String credentials = DatatypeConverter.printBase64Binary(credBytes);
    conn.setRequestProperty("Authorization", "Basic " + credentials);
    conn.setRequestProperty("User-Agent", userAgent);

    if (parameters != null) {
      conn.setDoOutput(true);
      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      String parametersString = jsonStringify(parameters);
      writer.write(parametersString);
      writer.close();
    }

    int statusCode = 0;
    try {
      conn.connect();
      statusCode = conn.getResponseCode();
    } catch (IOException e) {
      throw new VingdTransportException("Connecting to Vingd Broker failed.", e);
    }

    StringBuffer response = new StringBuffer();
    String jsonContent;
    try {
      InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
      BufferedReader in = new BufferedReader(reader);
      String line;
      while ((line = in.readLine()) != null) response.append(line);
      in.close();
      jsonContent = response.toString();
    } catch (IOException e) {
      throw new VingdTransportException("Communication with Vingd Broker failed.", e);
    } finally {
      conn.disconnect();
    }

    // return data response if request successful
    Map<String, Object> contentMap;
    try {
      contentMap = (Map<String, Object>) jsonParseMap(jsonContent);
    } catch (Exception e) {
      throw new VingdTransportException(
          "Non-JSON response or unexpected JSON structure.", "ParsingResponse", statusCode, e);
    }

    if (statusCode >= 200 && statusCode < 300) {
      Object data = contentMap.get("data");
      if (data == null) {
        throw new VingdTransportException("Invalid JSON error response.", "ParsingDataResponse");
      }
      return data;
    }

    // raise exception describing the vingd error condition
    String message, context;
    try {
      message = (String) contentMap.get("message");
      context = (String) contentMap.get("context");
    } catch (Exception e) {
      throw new VingdTransportException(
          "Invalid JSON error response.", "ParsingErrorResponse", statusCode, e);
    }
    throw new VingdOperationException(message, context, statusCode);
  }
コード例 #27
0
ファイル: HttpGetter.java プロジェクト: hrf1159/RavenD
  public static String httpsGet(String requestUrl, String requestMethod, String outputStr) {

    String jsonObject = null;

    StringBuffer buffer = new StringBuffer();

    try {

      // 创建SSLContext对象,并使用我们指定的信任管理器初始化

      TrustManager[] tm = {new HttpsTrustManager()};

      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

      sslContext.init(null, tm, new java.security.SecureRandom());

      // 从上述SSLContext对象中得到SSLSocketFactory对象

      SSLSocketFactory ssf = sslContext.getSocketFactory();

      URL url = new URL(requestUrl);

      HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();

      httpUrlConn.setSSLSocketFactory(ssf);
      httpUrlConn.setDoOutput(true);
      httpUrlConn.setDoInput(true);
      httpUrlConn.setUseCaches(false);

      // 设置请求方式(GET/POST)

      httpUrlConn.setRequestMethod(requestMethod);

      if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();

      // 当有数据需要提交时

      if (null != outputStr) {

        OutputStream outputStream = httpUrlConn.getOutputStream();
        // 注意编码格式,防止中文乱码

        outputStream.write(outputStr.getBytes("UTF-8"));
        outputStream.close();
      }

      // 将返回的输入流转换成字符串

      InputStream inputStream = httpUrlConn.getInputStream();

      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");

      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

      String str = null;

      while ((str = bufferedReader.readLine()) != null) {

        buffer.append(str);
      }

      bufferedReader.close();
      inputStreamReader.close();

      // 释放资源

      inputStream.close();
      inputStream = null;
      httpUrlConn.disconnect();
      jsonObject = buffer.toString();

    } catch (ConnectException ce) {

    } catch (Exception e) {
      e.printStackTrace();
    }

    return jsonObject;
  }