/**
   * http post 请求
   *
   * @param url 请求url
   * @param jsonStr post参数
   * @return HttpResponse请求结果实例
   */
  public static Response httpPost(String url, String jsonStr) {
    Response response = null;

    HttpsURLConnection httpsURLConnection = null;
    try {
      URL urlObj = new URL(url);
      httpsURLConnection = (HttpsURLConnection) urlObj.openConnection();
      httpsURLConnection.setRequestMethod("POST");
      httpsURLConnection.setConnectTimeout(BCCache.getInstance().connectTimeout);
      httpsURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
      httpsURLConnection.setDoOutput(true);
      httpsURLConnection.setChunkedStreamingMode(0);

      // start to post
      response = writeStream(httpsURLConnection, jsonStr);

      if (response == null) { // if post successfully

        response = readStream(httpsURLConnection);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();

      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (IOException e) {
      e.printStackTrace();

      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = new Response();
      response.content = ex.getMessage();
      response.code = -1;
    } finally {
      if (httpsURLConnection != null) httpsURLConnection.disconnect();
    }

    return response;
  }
  public static Response getPayPalAccessToken() {

    Response response = null;

    HttpsURLConnection httpsURLConnection = null;
    try {
      URL urlObj = new URL(getPayPalAccessTokenUrl());
      httpsURLConnection = (HttpsURLConnection) urlObj.openConnection();
      httpsURLConnection.setConnectTimeout(BCCache.getInstance().connectTimeout);
      httpsURLConnection.setRequestMethod("POST");
      httpsURLConnection.setRequestProperty("Accept", "application/json");
      httpsURLConnection.setRequestProperty(
          "Authorization",
          BCSecurityUtil.getB64Auth(
              BCCache.getInstance().paypalClientID, BCCache.getInstance().paypalSecret));
      httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      httpsURLConnection.setDoOutput(true);
      httpsURLConnection.setChunkedStreamingMode(0);

      response = writeStream(httpsURLConnection, "grant_type=client_credentials");
      if (response == null) {

        response = readStream(httpsURLConnection);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (IOException e) {
      e.printStackTrace();
      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } finally {
      if (httpsURLConnection != null) httpsURLConnection.disconnect();
    }

    return response;
  }
예제 #3
0
    // HTTP PUT change to the server
    // Return 0 on success
    // Return 1 on Android failure
    // Return 2 on server failure
    private void updateItem() {
      URL url;
      HttpsURLConnection urlConnection = null;
      int size;
      byte[] data;
      OutputStream out;
      String itemUrl = UPDATE_ITEM_URL + "/" + mItem.getId();

      try {
        url = new URL(itemUrl);
        urlConnection = (HttpsURLConnection) url.openConnection();

        // Set authentication instance ID
        urlConnection.setRequestProperty(
            MyConstants.HTTP_HEADER_INSTANCE_ID,
            InstanceID.getInstance(getApplicationContext()).getId());
        // Set content type
        urlConnection.setRequestProperty("Content-Type", "application/json");

        // To upload data to a web server, configure the connection for output using
        // setDoOutput(true). It will use POST if setDoOutput(true) has been called.
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("PUT");

        // Convert item to JSON string
        JSONObject jsonItem = new JSONObject();
        JSONObject jsonMember = new JSONObject();
        JSONArray jsonMembers = new JSONArray();
        jsonMember.put("attendant", change);
        if (change >= 1 && mPhoneNumber != null && !mPhoneNumber.isEmpty()) {
          jsonMember.put("phonenumber", mPhoneNumber);
        }
        jsonMembers.put(jsonMember);
        jsonItem.put("members", jsonMembers);
        data = jsonItem.toString().getBytes();

        // For best performance, you should call either setFixedLengthStreamingMode(int) when the
        // body length is known in advance, or setChunkedStreamingMode(int) when it is not.
        // Otherwise HttpURLConnection will be forced to buffer the complete request body in memory
        // before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.
        size = data.length;
        if (size > 0) {
          urlConnection.setFixedLengthStreamingMode(size);
        } else {
          // Set default chunk size
          urlConnection.setChunkedStreamingMode(0);
        }

        // Get the OutputStream of HTTP client
        out = new BufferedOutputStream(urlConnection.getOutputStream());
        // Copy from file to the HTTP client
        out.write(data);
        // Make sure to close streams, otherwise "unexpected end of stream" error will happen
        out.close();

        // Check canceled
        if (isCancelled()) {
          Log.d(LOG_TAG, "Updating item canceled");
          status = UpdateItemStatus.ANDROID_FAILURE;
          return;
        }

        // Set timeout
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);

        // Vernon debug
        Log.d(
            LOG_TAG,
            urlConnection.getRequestMethod()
                + " "
                + urlConnection.getURL().toString()
                + new String(data));

        // Send and get response
        // getResponseCode() will automatically trigger connect()
        int responseCode = urlConnection.getResponseCode();
        String responseMsg = urlConnection.getResponseMessage();
        Log.d(LOG_TAG, "Response " + responseCode + " " + responseMsg);
        if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
          Log.d(LOG_TAG, "Server says the item was closed");
          status = UpdateItemStatus.ITEM_CLOSED;
          return;
        }
        if (responseCode != HttpURLConnection.HTTP_OK) {
          Log.d(LOG_TAG, "Update item attendant " + change + " failed");
          status = UpdateItemStatus.SERVER_FAILURE;
          return;
        }

        // Vernon debug
        Log.d(LOG_TAG, "Update item attendant " + change + " successfully");

      } catch (Exception e) {
        e.printStackTrace();
        Log.d(LOG_TAG, "Update item failed because " + e.getMessage());
        status = UpdateItemStatus.ANDROID_FAILURE;
      } finally {
        if (urlConnection != null) {
          urlConnection.disconnect();
        }
      }
    }