Exemplo n.º 1
1
  /**
   * @param url
   * @param request
   * @param resContentHeaders
   * @param timeout
   * @return
   * @throws java.lang.Exception
   * @deprecated As of proxy release 1.0.10, replaced by {@link #sendRequestoverHTTPS( boolean
   *     isBusReq, URL url, String request, Map resContentHeaders, int timeout)}
   */
  public static String sendRequestOverHTTPS(
      URL url, String request, Map resContentHeaders, int timeout) throws Exception {

    // Set up buffers and streams
    StringBuffer buffy = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
      HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      // this makes the assumption that all https requests are going to the bus using UTF-8 encoding
      String encodedString =
          URLEncoder.encode(request, FastHttpClientConstants.HTTP_REQUEST_ENCODING);
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      out.write(FastHttpClientConstants.HTTP_REQUEST_POST_KEY.getBytes());
      out.write(encodedString.getBytes());
      out.flush();

      // Response
      // this mangles 2 or more byte characters
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      buffy = new StringBuffer(INPUT_BUFFER_LEN);
      int ch = 0;
      while ((ch = in.read()) > -1) {
        buffy.append((char) ch);
      }

      populateHTTPSHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return buffy == null ? null : buffy.toString();
  }
  /**
   * 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;
  }
Exemplo n.º 3
0
  /**
   * 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;
  }
Exemplo n.º 4
0
  /**
   * Parses the url connection.
   *
   * @param url the url
   * @param apiKey the api key
   * @param requestMethod the request method
   * @param data the data
   * @return the string
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws JSONException the jSON exception
   */
  public static String parseUrlConnection(String url, String requestMethod, String data)
      throws IOException, JSONException {

    URL u = new URL(url);
    HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
    uc.setRequestMethod(requestMethod);
    String authentication =
        "<DocuSignCredentials><Username>"
            + Data.USERNAME
            + "</Username><Password>"
            + Data.PASSWORD
            + "</Password><IntegratorKey>"
            + Data.INTEGRATOR_KEY
            + "</IntegratorKey></DocuSignCredentials>";
    uc.setRequestProperty("X-DocuSign-Authentication", authentication);
    uc.setRequestProperty("Content-type", "application/json");
    uc.setRequestProperty("Accept", "application/json");
    if (data != null) {
      uc.setDoOutput(true);
      OutputStreamWriter postData = new java.io.OutputStreamWriter(uc.getOutputStream());
      postData.write(data);
      postData.flush();
      postData.close();
    }
    InputStream is = uc.getInputStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      return jsonText;
    } finally {
      is.close();
    }
  }
Exemplo n.º 5
0
  public static void downloadPDF(String url, String downloadPath)
      throws IOException, JSONException {

    URL u = new URL(url);
    HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
    uc.setRequestMethod("GET");
    String authentication =
        "<DocuSignCredentials><Username>"
            + Data.USERNAME
            + "</Username><Password>"
            + Data.PASSWORD
            + "</Password><IntegratorKey>"
            + Data.INTEGRATOR_KEY
            + "</IntegratorKey></DocuSignCredentials>";
    uc.setRequestProperty("X-DocuSign-Authentication", authentication);
    uc.setRequestProperty("Content-type", "application/pdf");
    uc.setRequestProperty("Accept", "application/pdf");
    File file = new File(downloadPath);
    FileOutputStream fileOutput = new FileOutputStream(file);
    InputStream is = uc.getInputStream();
    try {
      byte[] buffer = new byte[1024];
      int bufferLength = 0; // used to store a temporary size of the
      // buffer
      while ((bufferLength = is.read(buffer)) > 0) {
        fileOutput.write(buffer, 0, bufferLength);
      }
      fileOutput.close();
    } finally {
      is.close();
    }
  }
Exemplo n.º 6
0
  // Get data given REST URL
  public String getData(String uri) {

    BufferedReader reader = null;
    try {
      URL url = new URL(uri);
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setRequestMethod("GET");
      StringBuilder sb = new StringBuilder();
      reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

      String line;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
          return null;
        }
      }
    }
  }
Exemplo n.º 7
0
  // Add a new user
  public String addUser(String uri, String j) {
    try {
      URL url = new URL(uri);
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setDoOutput(true);
      con.setDoInput(true);
      con.setRequestMethod("POST");

      OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
      out.write(j);
      out.flush();
      out.close();

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();

      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }

      Log.d("AddUserReponse", response.toString());
      in.close();

      return "success";
    } catch (Exception e) {
      e.printStackTrace();
      return "fail";
    }
  }
Exemplo n.º 8
0
  public void exec(HttpsCb cb) {

    try {
      if (!NetUtil.isConnected()) {
        ViewInject.toast("找不到网络了...");
        return;
      }
    } catch (Exception e) {
      return;
    }
    if (mSslContext == null) {
      try {
        mSslContext = initCertificate();
      } catch (Exception e) {
        e.printStackTrace();
        ViewInject.toast("init ssl failed");
        return;
      }
    }
    try {
      HttpsURLConnection conn = openConnection();
      int code = conn.getResponseCode();
      MLoger.debug("httpcode-->" + code);

      if (code == 200 || code == 201) { // 网络请求成功
        String data = parseResponse(conn.getInputStream());
        MLoger.debug("response data-->" + data);
        if (cb != null) cb.onResponse(data);
      } else {
        MLoger.debug("error httpcode-->" + code);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 9
0
 /**
  * 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;
 }
 private void assertUrlConnectionSucceeds(SSLContext context, String host, int port)
     throws Exception {
   URL url = new URL("https://" + host + ":" + port);
   HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
   connection.setSSLSocketFactory(context.getSocketFactory());
   connection.getInputStream();
 }
  public String getContent(URL url, boolean altercookies) {
    String s = "";
    try {
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setRequestProperty("Cookie", cookies); // Retain our sessoin
      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String input;
      while ((input = br.readLine()) != null) {
        s += input + "\n";
      }
      br.close();

      StringBuilder sb = new StringBuilder();

      // find the cookies in the response header from the first request
      List<String> cookie = con.getHeaderFields().get("Set-Cookie");
      if (cookie != null) {
        for (String cooki : cookie) {
          if (sb.length() > 0) {
            sb.append("; ");
          }

          // only want the first part of the cookie header that has the value
          String value = cooki.split(";")[0];
          sb.append(value);
        }
      }
      if (altercookies) cookies = sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return s;
  }
Exemplo n.º 12
0
 /* package */ String loadNetwork(String url) {
   InputStreamReader isr = null;
   BufferedReader br = null;
   try {
     HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
     isr = new InputStreamReader(con.getInputStream());
     br = new BufferedReader(isr);
     String line = null;
     StringBuilder sb = new StringBuilder();
     while ((line = br.readLine()) != null) {
       sb.append(line);
     }
     return sb.toString();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (isr != null) {
       try {
         isr.close();
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
     if (br != null) {
       try {
         br.close();
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
   return null;
 }
  /**
   * Executa a operação da API informando um Builder para a requisição e resposta.
   *
   * @param requestBuilder é uma instância de {@link AkatusRequestBuilder} responsável pela criação
   *     do corpo da requisição.
   * @param responseBuilder é uma instância de {@link AkatusResponseBuilder} responsável pela
   *     criação do objeto que representa a resposta.
   * @return Uma instância de {@link AkatusResponse} com a resposta da operação.
   */
  public AkatusResponse execute(
      AkatusRequestBuilder requestBuilder, AkatusResponseBuilder responseBuilder) {

    AkatusResponse response = new AkatusResponse();

    try {
      final URL url = new URL(akatus.getHost() + getPath());
      final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", requestBuilder.getContentType());

      final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

      writer.write(requestBuilder.build(this));
      writer.flush();

      try {
        response = responseBuilder.build(readResponse(connection.getInputStream()));
      } catch (final IOException e) {
        response = responseBuilder.build(readResponse(connection.getErrorStream()));
      }
    } catch (final Exception e) {
      Logger.getLogger(AkatusOperation.class.getName())
          .throwing(this.getClass().getName(), "execute", e);
    }

    return response;
  }
Exemplo n.º 14
0
 /**
  * 方法名: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;
 }
Exemplo n.º 15
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);
 }
Exemplo n.º 16
0
  public void getAccessToken(String code) {
    try {
      String accessTokenString =
          FacebookOAuth2Details.accessTokenUri
              + "?client_id="
              + FacebookOAuth2Details.clientId
              + "&client_secret="
              + FacebookOAuth2Details.clientSecret
              + "&code="
              + code
              + "&redirect_uri="
              + FacebookOAuth2Details.redirectUri;

      URL myurl = new URL(accessTokenString);
      HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
      InputStream ins = con.getInputStream();
      InputStreamReader isr = new InputStreamReader(ins, "UTF-8");

      JSONParser parser = new JSONParser();
      JSONObject jObject = (JSONObject) parser.parse(isr);
      accessToken = jObject.get("access_token").toString();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 17
0
  /**
   * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议
   *
   * @throws CertificateException
   * @throws IOException
   * @throws KeyStoreException
   * @throws NoSuchAlgorithmException
   * @throws KeyManagementException
   */
  public void initSSL()
      throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
          KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream in = getAssets().open("load-der.crt");
    Certificate ca = cf.generateCertificate(in);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null, null);
    keystore.setCertificateEntry("ca", ca);

    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keystore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version");
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    InputStream input = urlConnection.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = reader.readLine()) != null) {
      result.append(line);
    }
    Log.e("TTTT", result.toString());
  }
Exemplo n.º 18
0
  public static ArrayList<Deal> getDeals(
      String url, final RequestQueue requestQueue, int startPage, int endPage) {
    RequestFuture<String> requestFuture = RequestFuture.newFuture();
    ArrayList<Deal> deals = new ArrayList<>((endPage - startPage) * 10);

    String pageParam = null;
    for (int i = startPage; i < endPage; i++) {
      String xml = null;
      pageParam = String.format(L.PAGE_PARAM, i);

      StringRequest stringRequest =
          new StringRequest(Request.Method.GET, url + pageParam, requestFuture, requestFuture);

      try {
        requestQueue.add(stringRequest);
        xml = requestFuture.get(30000, TimeUnit.MILLISECONDS);
        HttpsURLConnection connection = getFeed(url + pageParam);
        try {

          deals.addAll(DomXmlMapper.xmlToDeal(connection.getInputStream()));
        } catch (Exception e) {

        } finally {
          connection.disconnect();
          Thread.sleep(100);
        }
        //                deals.addAll(DomXmlMapper.xmlToDeal(xml));

      } catch (Exception e) {
        L.d(TAG, "Error while retreiving feed", e);
      }
    }
    return deals;
  }
Exemplo n.º 19
0
  public User getUserFromSocNet() {
    try {

      String methodString = FacebookOAuth2Details.methodUri + "me?access_token=" + accessToken;
      URL newUrl = new URL(methodString);

      HttpsURLConnection con = (HttpsURLConnection) newUrl.openConnection();
      InputStream ins = con.getInputStream();

      InputStreamReader newIsr = new InputStreamReader(ins, "UTF-8");
      JSONParser parser = new JSONParser();
      JSONObject jsonUser = (JSONObject) parser.parse(newIsr);

      userId = jsonUser.get("id").toString();

      User user = new User();
      user.setSocialId("fb" + userId);

      user.setFirstName(jsonUser.get("first_name").toString());

      user.setLastName(jsonUser.get("last_name").toString());
      if (jsonUser.get("email") != null) {

        user.setEmail(jsonUser.get("email").toString());
      }
      return user;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Exemplo n.º 20
0
  public String doGet(String urlstr) throws IOException {
    URL url = new URL(urlstr);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    fetchReqMap(connection); // 设置请求属性
    connection.setReadTimeout(timeout);
    connection.setDoOutput(false); // true for POST, false for GET
    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);

    String aLine = null;
    String ret = "";
    InputStream is = connection.getInputStream();
    BufferedReader aReader = new BufferedReader(new InputStreamReader(is, this.getRespEncode()));

    while ((aLine = aReader.readLine()) != null) {
      ret += aLine + "\r\n";
      ;
    }

    aReader.close();
    connection.disconnect();

    return ret;
  }
Exemplo n.º 21
0
  public String doPost(String urlstr, byte data[]) throws IOException {
    URL url = new URL(urlstr);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    fetchReqMap(connection);
    //
    // connection.setRequestProperty("SOAPAction","https://hms.wellcare.cn:8443/services/EnergyData");

    connection.setReadTimeout(timeout);
    connection.setDoOutput(true); // true for POST, false for GET
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);

    // 写入post数据
    OutputStream out = connection.getOutputStream();
    out.write(data);

    // 读出反馈结果
    String aLine = null;
    String ret = "";
    InputStream is = connection.getInputStream();
    BufferedReader aReader = new BufferedReader(new InputStreamReader(is, this.getRespEncode()));

    while ((aLine = aReader.readLine()) != null) {
      ret += aLine + "\r\n";
    }

    aReader.close();
    connection.disconnect();

    return ret;
  }
Exemplo n.º 22
0
  public User getUserFromSocNet() {
    try {

      String methodString =
          VKOAuth2Details.methodUri
              + "users.get?user_ids="
              + userId
              + "&fields=city,sex,bdate&v=5.28&access_token="
              + accessToken
              + "&lang=ua";
      URL newUrl = new URL(methodString);
      HttpsURLConnection con = (HttpsURLConnection) newUrl.openConnection();
      InputStream ins = con.getInputStream();

      InputStreamReader newIsr = new InputStreamReader(ins, "UTF-8");
      JSONParser parser = new JSONParser();
      JSONObject response = (JSONObject) parser.parse(newIsr);
      JSONArray jsonUsers = (JSONArray) response.get("response");
      JSONObject jsonUser = (JSONObject) jsonUsers.get(0);

      User user = new User();
      user.setSocialId("vk" + userId);
      user.setEmail(email);
      user.setFirstName(jsonUser.get("first_name").toString());

      user.setLastName(jsonUser.get("last_name").toString());
      return user;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  public GetRecurringPaymentsProfileDetailsResposta getRecurringPaymentsProfileDetails(
      Map<String, String[]> parametros) throws IllegalStateException {

    StringBuilder param = new StringBuilder();
    GetRecurringPaymentsProfileDetailsResposta resp = null;

    try {
      HttpsURLConnection conn =
          Util.getConexaoHttps((String) parametros.get("NAOENVIAR_ENDPOINT")[0]);

      logger.info("Parametros da chamada GetRecurringPaymentsProfileDetails:");
      for (Map.Entry<String, String[]> item : parametros.entrySet()) {
        if (podeEnviarParametro(item.getKey(), item.getValue()[0])) {
          param.append(item.getKey() + "=" + URLEncoder.encode(item.getValue()[0], "UTF-8") + "&");
          logger.info("     " + item.getKey() + ": " + item.getValue()[0] + "&");
        }
      }

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
      logger.info("Chamada a: " + conn.getURL() + " com os parametros: " + param.toString());

      writer.write(param.toString());
      writer.flush();
      writer.close();

      InputStreamReader in = new InputStreamReader(conn.getInputStream());

      param = null;
      param = new StringBuilder();

      BufferedReader reader = new BufferedReader(in);

      String data;

      logger.info("Retorno da chamada: ");
      while ((data = reader.readLine()) != null) {
        param.append(data);
      }

      /*if (data.contains("TOKEN")) {
      param.append("==================================================");
      }*/

      data = param.toString();

      GetRecurringPaymentsProfileDetailsParser parser =
          GetRecurringPaymentsProfileDetailsParser.getInstance();
      resp = parser.parse(data);

      logger.info(data);

    } catch (IOException ex) {
      logger.fatal(
          "Erro ao executar GetRecurringPaymentsProfileDetails: " + ex.getLocalizedMessage(), ex);
    }

    return resp;
  }
  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;
  }
  /**
   * Executa o metodo SetExpressCheckout
   *
   * @param parametros Parametros recebido do formulario ou do sistema do cliente
   */
  public SetExpressCheckoutResposta setExpressCheckout(Map<String, String[]> parametros)
      throws IllegalStateException {

    StringBuilder param = new StringBuilder();
    SetExpressCheckoutResposta resp = null;

    if (this.getCredenciais() == null) {
      throw new IllegalStateException("As credencais do merchant nao foram informadas.");
    }

    try {
      HttpsURLConnection conn =
          Util.getConexaoHttps((String) parametros.get("NAOENVIAR_ENDPOINT")[0]);

      logger.info("Parametros da chamada:");
      logger.info("Conectando-se a " + conn.getURL());
      for (Map.Entry<String, String[]> item : parametros.entrySet()) {
        if (podeEnviarParametro(item.getKey(), item.getValue()[0])) {
          param.append(item.getKey() + "=" + URLEncoder.encode(item.getValue()[0], "UTF-8") + "&");
          logger.info("     " + item.getKey() + ": " + item.getValue()[0] + "&");
        }
      }

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
      // logger.info("Chamada: " + param.toString());

      writer.write(param.toString());
      writer.flush();
      writer.close();

      InputStreamReader in = new InputStreamReader(conn.getInputStream());

      param = null;
      param = new StringBuilder();

      BufferedReader reader = new BufferedReader(in);

      String data;

      logger.info("Retorno da chamada: ");
      while ((data = reader.readLine()) != null) {
        param.append(data);
      }

      data = param.toString();

      SetExpressCheckoutParser parser = SetExpressCheckoutParser.getInstance();
      resp = parser.parse(data);

      // logger.debug("Resposta do SetExpressCheckout: " + resp.toString());

    } catch (IOException ex) {
      logger.fatal("Erro ao executar SetExpressCheckout: " + ex.getLocalizedMessage(), ex);
    }

    return resp;
  }
Exemplo n.º 26
0
  public ServiceUser getServiceUser(String accessToken, String refreshToken) {
    ServiceUser result = null;

    try {
      String url =
          "https://api.linkedin.com/v1/people/~:(first-name,last-name,formatted-name,id,main-address,email-address,im-accounts,twitter-accounts,site-standard-profile-request,location,picture-url)";
      url += "?format=json&oauth2_access_token=" + accessToken;

      URL obj = new URL(url);
      HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
      con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      con.setRequestMethod("GET");

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

      JsonParser parser = new JsonParser();
      JsonElement jsonUserInfo = parser.parse(in);
      if (jsonUserInfo != null && (jsonUserInfo instanceof JsonObject)) {
        result = new ServiceUser();
        result.setAreRoleNamesAccurate(useRoleNames);

        // This is set here in the case we had to refresh this access token.
        result.setAccessToken(accessToken);

        result.setId(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "id"));

        result.setFirstName(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "firstName"));
        result.setLastName(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "lastName"));
        result.setName(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "formattedName"));

        result.setAvatarUrl(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "pictureUrl"));

        List<ServiceIdentifier> identifiers = new ArrayList<ServiceIdentifier>();
        identifiers.add(new ServiceIdentifier(ServiceIdentifier.LINKED_ID, result.getId()));
        result.setIdentifiers(identifiers);

        List<String> emails = new ArrayList<String>();
        String email = getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "emailAddress");
        emails.add(email);
        identifiers.add(new ServiceIdentifier(ServiceIdentifier.EMAIL, email));
        result.setEmails(emails);
        result.setLink(
            getJsonObjectStringValue(
                jsonUserInfo.getAsJsonObject().getAsJsonObject("siteStandardProfileRequest"),
                "url"));
        result.setLocale(
            getJsonObjectStringValue(
                jsonUserInfo.getAsJsonObject().getAsJsonObject("location"), "name"));
      } else {
        log.debug("Unable to get Google Profile Information. User information was not populated");
      }
    } catch (Exception e) {
      log.error("Error getting ServiceUser", e);
    }

    return result;
  }
Exemplo n.º 27
0
  public static String sendRequestOverHTTPS(
      boolean isBusReq, URL url, String request, Map resContentHeaders, int timeout)
      throws Exception {

    // Set up buffers and streams
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    String fullResponse = null;

    try {
      HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      sendRequestString(isBusReq, out, request);

      // recv response
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      String contentType = urlc.getHeaderField("Content-Type");
      fullResponse = receiveResponseString(in, contentType);

      out.close();
      in.close();

      populateHTTPSHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return fullResponse;
  }
Exemplo n.º 28
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;
  }
Exemplo n.º 29
0
  /**
   * 发起https请求并获取结果
   *
   * @param requestUrl 请求地址
   * @param requestMethod 请求方式(GET、POST)
   * @param outputStr 提交的数据
   * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
   */
  public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    //
    log.info("https请求url是" + requestUrl);
    try {
      // 创建SSLContext对象,并使用我们指定的信任管理器初始化
      TrustManager[] tm = {new MyX509TrustManager()};
      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;
      StringBuffer buffer = new StringBuffer();
      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("连接超时", ce);
    } catch (Exception e) {
      log.error("请求异常", e);
    }
    return jsonObject;
  }
  /**
   * The main RESTful GET method; the other one ({@link #make_restful_get(String, String, int)})
   * calls this one with a pre-populated logging parameter.
   *
   * @param baseUrl A {@link String} URL to request from.
   * @param tag A {@link String} tag for logging/analytics purposes.
   * @param timeout An {@link Integer} value containing the number of milliseconds to wait before
   *     considering a server request to have timed out.
   * @param log A {@link Boolean} value that specifies whether debug logging should be enabled for
   *     this request or not.
   * @return A {@link ServerResponse} object containing the result of the RESTful request.
   */
  private ServerResponse make_restful_get(
      String baseUrl, String tag, int timeout, int retryNumber, boolean log) {
    String modifiedUrl = baseUrl;
    JSONObject getParameters = new JSONObject();
    HttpsURLConnection connection = null;
    if (timeout <= 0) {
      timeout = DEFAULT_TIMEOUT;
    }
    if (addCommonParams(getParameters, retryNumber)) {
      modifiedUrl += this.convertJSONtoString(getParameters);
    } else {
      return new ServerResponse(tag, NO_BRANCH_KEY_STATUS);
    }

    try {
      if (log) PrefHelper.Debug("BranchSDK", "getting " + modifiedUrl);
      URL urlObject = new URL(modifiedUrl);
      connection = (HttpsURLConnection) urlObject.openConnection();
      connection.setConnectTimeout(timeout);
      connection.setReadTimeout(timeout);

      if (connection.getResponseCode() >= 500 && retryNumber < prefHelper_.getRetryCount()) {
        try {
          Thread.sleep(prefHelper_.getRetryInterval());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        retryNumber++;
        return make_restful_get(baseUrl, tag, timeout, retryNumber, log);
      } else {
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK
            && connection.getErrorStream() != null) {
          return processEntityForJSON(
              connection.getErrorStream(), connection.getResponseCode(), tag, log, null);
        } else {
          return processEntityForJSON(
              connection.getInputStream(), connection.getResponseCode(), tag, log, null);
        }
      }
    } catch (SocketException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (UnknownHostException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (IOException ex) {
      if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage());
      return new ServerResponse(tag, 500);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }