コード例 #1
0
  /**
   * Method used for API calls, with the request type, body, headers, and callback as parameters.
   */
  public void apiCall(
      String method,
      String url,
      LinkedHashMap<String, String> body,
      HashMap<String, String> headerMap,
      Callback callback) {
    try {
      OkHttpClient client = new OkHttpClient();
      // Check if the Platform is authorized, and add the authorization header
      this.isAuthorized();
      headerMap.put("Authorization", this.getAuthHeader());
      // Generate the proper url to be passed into the request
      HashMap<String, String> options = new HashMap<>();
      options.put("addServer", "true");
      String apiUrl = apiURL(url, options);

      Request.Builder requestBuilder = new Request.Builder();
      // Add all the headers to the Request.Builder from the headerMap
      for (Map.Entry<String, String> entry : headerMap.entrySet()) {
        requestBuilder.addHeader(entry.getKey(), entry.getValue());
      }
      Request request = null;
      if (method.toUpperCase().equals("GET")) {
        request = requestBuilder.url(apiUrl).build();
      } else if (method.toUpperCase().equals("DELETE")) {
        request = requestBuilder.url(apiUrl).delete().build();
      } else {
        // For POST and PUT requests, find and set what MediaType the body is
        MediaType mediaType;
        if (headerMap.containsValue("application/json")) {
          mediaType = JSON_TYPE_MARKDOWN;
        } else if (headerMap.containsValue("multipart/mixed")) {
          mediaType = MULTI_TYPE_MARKDOWN;
        } else {
          mediaType = MEDIA_TYPE_MARKDOWN;
        }
        String bodyString = getBodyString(body, mediaType);
        if (method.toUpperCase().equals("POST")) {
          request =
              requestBuilder.url(apiUrl).post(RequestBody.create(mediaType, bodyString)).build();
        } else if (method.toUpperCase().equals("PUT")) {
          request =
              requestBuilder.url(apiUrl).put(RequestBody.create(mediaType, bodyString)).build();
        }
      }
      // Make OKHttp request call, that returns response to the callback
      client.newCall(request).enqueue(callback);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #2
0
ファイル: OkApacheClient.java プロジェクト: dyglcc/mmwd
  private static Request transformRequest(HttpRequest request, Object tag) {
    Request.Builder builder = new Request.Builder();

    RequestLine requestLine = request.getRequestLine();
    String method = requestLine.getMethod();
    builder.url(requestLine.getUri());

    String contentType = null;
    for (Header header : request.getAllHeaders()) {
      String name = header.getName();
      if ("Content-Type".equals(name)) {
        contentType = header.getValue();
      } else {
        builder.header(name, header.getValue());
      }
    }

    RequestBody body = null;
    if (request instanceof HttpEntityEnclosingRequest) {
      HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
      if (entity != null) {
        // Wrap the entity in a custom Body which takes care of the content, length, and type.
        body = new HttpEntityBody(entity, contentType);

        Header encoding = entity.getContentEncoding();
        if (encoding != null) {
          builder.header(encoding.getName(), encoding.getValue());
        }
      }
    }
    builder.method(method, body);
    builder.tag(tag);

    return builder.build();
  }
コード例 #3
0
  @Override
  public Request buildRequest() {
    Request.Builder builder = new Request.Builder();
    String url =
        getUrl() + "?key=" + cacHttpClient.getApiKey() + "&login=" + cacHttpClient.getLogin();
    builder.url(url);

    return builder.build();
  }
コード例 #4
0
  @Override
  public Call getDetail(String videoId, Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(API_URL + "movie_details.json?movie_id=" + videoId);
    requestBuilder.addHeader("Host", "xor.image.yt");
    requestBuilder.tag(MEDIA_CALL);

    return fetchDetail(requestBuilder, callback);
  }
コード例 #5
0
 @Override
 protected Request buildRequest() {
   if (TextUtils.isEmpty(url)) {
     throw new IllegalArgumentException("url can not be empty!");
   }
   Request.Builder builder = new Request.Builder();
   appendHeaders(builder, headers);
   builder.url(url).tag(tag).post(requestBody);
   return builder.build();
 }
コード例 #6
0
ファイル: OkHttpGetRequest.java プロジェクト: siahewei/Ants
 @Override
 protected Request buildRequest() {
   if (TextUtils.isEmpty(url)) {
     throw new IllegalArgumentException("url can not be empty!");
   }
   // append params , if necessary
   url = appendParams(url, params);
   Request.Builder builder = new Request.Builder();
   // add headers , if necessary
   appendHeaders(builder, headers);
   builder.url(url).tag(tag);
   return builder.build();
 }
コード例 #7
0
 public KoalaDownloadTask build() {
   Map<String, String> params = new HashMap<String, String>();
   Map<String, String> headers = new HashMap<String, String>();
   Request.Builder builder = new Request.Builder();
   if (task.req != null) {
     KoalaHttpType type = task.req.getClass().getAnnotation(KoalaHttpType.class);
     if (type != null) {
       KoalaHttpUtils.getParams(task.req, task.req.getClass(), params, headers);
       if (headers.size() > 0) {
         Set<Map.Entry<String, String>> set = params.entrySet();
         Iterator<Map.Entry<String, String>> iterator = set.iterator();
         while (iterator.hasNext()) {
           Map.Entry<String, String> maEntry = iterator.next();
           builder.addHeader(maEntry.getKey(), maEntry.getValue());
         }
       }
       if (params.size() > 0) {
         if (type.value() == KoalaRequestType.GET) {
           task.url += ("?" + KoalaHttpUtils.getNameValuePair(params));
         } else if (type.value() == KoalaRequestType.POST) {
           Set<Map.Entry<String, String>> set = params.entrySet();
           Iterator<Map.Entry<String, String>> iterator = set.iterator();
           FormEncodingBuilder bodyBuilder = new FormEncodingBuilder();
           while (iterator.hasNext()) {
             Map.Entry<String, String> maEntry = iterator.next();
             bodyBuilder.add(maEntry.getKey(), maEntry.getValue());
           }
           builder.post(bodyBuilder.build());
         }
       }
     }
     task.url = KoalaHttpUtils.buildUrl(task.url, task.req);
     KoalaRequestTag tag = task.req.getClass().getAnnotation(KoalaRequestTag.class);
     if (tag != null) {
       if (TextUtils.isEmpty(tag.value())) {
         builder.tag(SecurityMD5.ToMD5(task.url));
       } else {
         builder.tag(tag);
       }
     } else {
       builder.tag(SecurityMD5.ToMD5(task.url));
     }
   } else {
     builder.tag(SecurityMD5.ToMD5(task.url));
   }
   builder.url(task.url);
   task.request = builder.build();
   task.tag = task.request.tag();
   return task;
 }
コード例 #8
0
 private boolean generateFallback(Request.Builder requestBuilder) {
   String url = requestBuilder.build().urlString();
   if (url.contains(MIRROR_URL2)) {
     return false;
   } else if (url.contains(MIRROR_URL)) {
     url = url.replace(MIRROR_URL, MIRROR_URL2);
     CURRENT_URL = MIRROR_URL2;
   } else {
     url = url.replace(API_URL, MIRROR_URL);
     CURRENT_URL = MIRROR_URL;
   }
   requestBuilder.url(url);
   return true;
 }
コード例 #9
0
  @Override
  public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    OkHttpClient client = okHttpClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder =
        new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();

    for (final String name : headers.keySet()) {
      okHttpRequestBuilder.addHeader(name, headers.get(name));
    }

    for (final String name : additionalHeaders.keySet()) {
      okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus =
        new BasicStatusLine(
            parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(),
            okHttpResponse.message());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();

    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
      final String name = responseHeaders.name(i), value = responseHeaders.value(i);

      if (name != null) {
        response.addHeader(new BasicHeader(name, value));
      }
    }

    return response;
  }
コード例 #10
0
    @Override
    protected String doInBackground(Void... params) {
      try {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(myURL).build();
        Response response = okHttpClient.newCall(request).execute();
        return response.body().string();

      } catch (Exception e) {

        Log.d("Spinner", "e doInBack ==> " + e.toString());
        return null;
      }
    }
コード例 #11
0
 /** POST request set up for making authorization calls */
 public void authCall(
     String url,
     LinkedHashMap<String, String> body,
     HashMap<String, String> headerMap,
     Callback callback) {
   OkHttpClient client = new OkHttpClient();
   Request.Builder requestBuilder = new Request.Builder();
   for (Map.Entry<String, String> entry : headerMap.entrySet()) {
     requestBuilder.addHeader(entry.getKey(), entry.getValue());
   }
   Request request = null;
   MediaType mediaType = MEDIA_TYPE_MARKDOWN;
   String bodyString = getBodyString(body, mediaType);
   HashMap<String, String> options = new HashMap<>();
   options.put("addServer", "true");
   String apiUrl = apiURL(url, options);
   request = requestBuilder.url(apiUrl).post(RequestBody.create(mediaType, bodyString)).build();
   client.newCall(request).enqueue(callback);
 }
コード例 #12
0
ファイル: MainActivity.java プロジェクト: onefoto/Http1
    @Override
    protected String doInBackground(String... params) {
      OkHttpClient okHttpClient = new OkHttpClient();

      Request.Builder builder = new Request.Builder();
      Request request = builder.url("http://192.168.1.94/check2.php").build();

      try {
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
          return response.body().string();
        } else {
          return "Not Success - code : " + response.code();
        }
      } catch (IOException e) {
        e.printStackTrace();
        return "Error - " + e.getMessage();
      }
    }
コード例 #13
0
  @Override
  protected Request convert(HttpRequest request) throws IOException, InterruptedException {
    Request.Builder builder = new Request.Builder();

    builder.url(request.getEndpoint().toString());
    populateHeaders(request, builder);

    RequestBody body = null;
    Payload payload = request.getPayload();

    if (payload != null) {
      Long length =
          checkNotNull(payload.getContentMetadata().getContentLength(), "payload.getContentLength");
      if (length > 0) {
        body = generateRequestBody(request, payload);
      }
    }

    builder.method(request.getMethod(), body);

    return builder.build();
  }
コード例 #14
0
  @Override
  public Call getDetail(String videoId, final Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(API_URLS[CURRENT_API] + "show/" + videoId);
    requestBuilder.tag(MEDIA_CALL);

    return enqueue(
        requestBuilder.build(),
        new com.squareup.okhttp.Callback() {
          @Override
          public void onFailure(Request request, IOException e) {
            callback.onFailure(e);
          }

          @Override
          public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
              String responseStr = response.body().string();
              LinkedTreeMap<String, Object> map = mGson.fromJson(responseStr, LinkedTreeMap.class);
              EZTVReponse result = new EZTVReponse(map);
              if (map == null) {
                callback.onFailure(new NetworkErrorException("Empty response"));
              } else {
                ArrayList<Media> formattedData = result.formatDetailForPopcorn();

                if (formattedData.size() > 0) {
                  callback.onSuccess(null, formattedData, true);
                  return;
                }
                callback.onFailure(new IllegalStateException("Empty list"));
                return;
              }
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to EZTVAPI"));
          }
        });
  }
コード例 #15
0
  @Override
  public Call getList(
      final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    final ArrayList<Media> currentList;
    if (existingList == null) {
      currentList = new ArrayList<>();
    } else {
      currentList = (ArrayList<Media>) existingList.clone();
    }

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("limit", "30"));

    if (filters == null) {
      filters = new Filters();
    }

    if (filters.keywords != null) {
      params.add(new NameValuePair("keywords", filters.keywords));
    }

    if (filters.genre != null) {
      params.add(new NameValuePair("genre", filters.genre));
    }

    if (filters.order == Filters.Order.ASC) {
      params.add(new NameValuePair("order", "asc"));
    } else {
      params.add(new NameValuePair("order", "desc"));
    }

    String sort = "";
    switch (filters.sort) {
      default:
      case POPULARITY:
        sort = "popularity";
        break;
      case TRENDING:
        sort = "trending";
        break;
      case YEAR:
        sort = "year";
        break;
      case DATE:
        sort = "updated";
        break;
      case RATING:
        sort = "rating";
        break;
      case ALPHABET:
        sort = "name";
        break;
    }

    params.add(new NameValuePair("sort", sort));

    String url = API_URLS[CURRENT_API] + "shows/";
    if (filters.page != null) {
      url += filters.page;
    } else {
      url += "1";
    }

    Request.Builder requestBuilder = new Request.Builder();
    String query = buildQuery(params);
    requestBuilder.url(url + "?" + query);
    requestBuilder.tag(MEDIA_CALL);

    return fetchList(currentList, requestBuilder, filters, callback);
  }
コード例 #16
0
  public void clickAddCheckList(View view) {
    odoString = odoEditText.getText().toString().trim();
    deepString = deepEditText.getText().toString().trim();
    presureString = presureEditText.getText().toString().trim();
    // commentString = commentEditText.getText().toString().trim();
    int month = checkDatePicker.getMonth() + 1;
    dateString = checkDatePicker.getYear() + "-" + month + "-" + checkDatePicker.getDayOfMonth();

    reasonNameString = reason1Spinner.getSelectedItem().toString();
    reasonName2String = reason2Spinner.getSelectedItem().toString();

    if (reasonNameString.equals("--select reason--")) {

    } else {
      if (reasonNameString.equals(reasonName2String)
          || reasonName2String.equals(reasonNameString)) {
        reasonNameString = reasonNameString.toString();
        reasonName2String = "";
      } else {
        reasonNameString = reasonNameString.toString();
        reasonName2String = reasonName2String.toString();
      }
    }
    if (reasonName2String.equals("--select reason--")) {

    } else {
      if (reasonNameString.equals(reasonName2String)
          || reasonName2String.equals(reasonNameString)) {
        reasonNameString = reasonNameString.toString();
        reasonName2String = "";
      } else {
        reasonNameString = reasonNameString.toString();
        reasonName2String = reasonName2String.toString();
      }
    }

    // reasonIdString = reason1Spinner.get
    Log.d("Date", dateString);
    Log.d("Spinner", reasonNameString + " :: Spinner 2 ::" + reasonName2String);

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody =
        new FormEncodingBuilder()
            .add("isAdd", "true")
            .add("odo", odoString)
            .add("deepTread", deepString)
            .add("presure", presureString)
            .add("checkDate", dateString)
            .add("tire_id", tireIdString)
            .add("username", username)
            .add("reason1", reasonNameString)
            .add("reason2", reasonName2String)
            .build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(url).post(requestBody).build();

    Call call = okHttpClient.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {
            Log.d("Call", "Failure");
          }

          @Override
          public void onResponse(Response response) throws IOException {
            Log.d("Call", "Success");
            runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    Toast.makeText(
                            AddCheckListActivity.this,
                            "Add Checklist Successful!!",
                            Toast.LENGTH_SHORT)
                        .show();
                  }
                });

            finish();
          }
        });
  }
コード例 #17
0
ファイル: OKHTTPBackend.java プロジェクト: Rroia/RedReader
  @Override
  public Request prepareRequest(final Context context, final RequestDetails details) {

    final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();

    final List<PostField> postFields = details.getPostFields();

    if (postFields != null) {
      builder.post(
          RequestBody.create(
              MediaType.parse("application/x-www-form-urlencoded"),
              PostField.encodeList(postFields)));

    } else {
      builder.get();
    }

    builder.url(details.getUrl().toString());
    builder.cacheControl(CacheControl.FORCE_NETWORK);

    final AtomicReference<Call> callRef = new AtomicReference<>();

    return new Request() {

      public void executeInThisThread(final Listener listener) {

        final Call call = mClient.newCall(builder.build());
        callRef.set(call);

        try {

          final Response response;

          try {
            response = call.execute();
          } catch (IOException e) {
            listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null);
            return;
          }

          final int status = response.code();

          if (status == 200 || status == 202) {

            final ResponseBody body = response.body();
            final InputStream bodyStream;
            final Long bodyBytes;

            if (body != null) {
              bodyStream = body.byteStream();
              bodyBytes = body.contentLength();

            } else {
              // TODO error
              bodyStream = null;
              bodyBytes = null;
            }

            final String contentType = response.header("Content-Type");

            listener.onSuccess(contentType, bodyBytes, bodyStream);

          } else {
            listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status);
          }

        } catch (Throwable t) {
          listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null);
        }
      }

      @Override
      public void cancel() {
        final Call call = callRef.getAndSet(null);
        if (call != null) {
          call.cancel();
        }
      }

      @Override
      public void addHeader(final String name, final String value) {
        builder.addHeader(name, value);
      }
    };
  }
コード例 #18
0
  @Override
  public Call getList(
      final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    final ArrayList<Media> currentList;
    if (existingList == null) {
      currentList = new ArrayList<>();
    } else {
      currentList = (ArrayList<Media>) existingList.clone();
    }

    ArrayList<NameValuePair> params = new ArrayList<>();
    params.add(new NameValuePair("limit", "30"));

    if (filters == null) {
      filters = new Filters();
    }

    if (filters.keywords != null) {
      params.add(new NameValuePair("query_term", filters.keywords));
    }

    if (filters.genre != null) {
      params.add(new NameValuePair("genre", filters.genre));
    }

    if (filters.order == Filters.Order.ASC) {
      params.add(new NameValuePair("order_by", "asc"));
    } else {
      params.add(new NameValuePair("order_by", "desc"));
    }

    String sort;
    switch (filters.sort) {
      default:
      case POPULARITY:
        sort = "seeds";
        break;
      case YEAR:
        sort = "year";
        break;
      case DATE:
        sort = "date_added";
        break;
      case RATING:
        sort = "rating";
        break;
      case ALPHABET:
        sort = "title";
        break;
    }

    params.add(new NameValuePair("sort_by", sort));

    if (filters.page != null) {
      params.add(new NameValuePair("page", Integer.toString(filters.page)));
    }

    Request.Builder requestBuilder = new Request.Builder();
    String query = buildQuery(params);
    requestBuilder.url(CURRENT_URL + "list_movies.json?" + query);
    requestBuilder.tag(MEDIA_CALL);

    return fetchList(currentList, requestBuilder, filters, callback);
  }