Java 类com.squareup.okhttp.Callback 实例源码

项目:rkt-launcher    文件:ClientTest.java   
@Test
public void shouldSendGetRequest() throws ExecutionException, InterruptedException {
  final Request request = new com.squareup.okhttp.Request.Builder()
      .url(URI)
      .method("GET", null)
      .build();
  when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
  doAnswer(invocation -> {
    final Callback callback = invocation.getArgument(0);
    callback.onResponse(new Response.Builder()
                            .request(request)
                            .protocol(Protocol.HTTP_1_1)
                            .code(Status.OK.code())
                            .message("OK")
                            .body(ResponseBody.create(CONTENT_TYPE, "{}"))
                            .header("foo", "bar")
                            .build());
    return Void.TYPE;
  }).when(call).enqueue(isA(Callback.class));
  final com.spotify.apollo.Response<ByteString> response =
      client.send(com.spotify.apollo.Request.forUri(URI, "GET")).toCompletableFuture().get();
  verify(okHttpClient, never()).setReadTimeout(anyLong(), any());

  assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload());
  assertEquals(Optional.of("bar"), response.header("foo"));
}
项目:rkt-launcher    文件:ClientTest.java   
@Test
public void shouldSendGetRequestAndReceiveException() {
  final Request request = new com.squareup.okhttp.Request.Builder()
      .url(URI)
      .method("GET", null)
      .build();
  when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
  doAnswer(invocation -> {
    final Callback callback = invocation.getArgument(0);
    callback.onFailure(request, new IOException());
    return Void.TYPE;
  }).when(call).enqueue(isA(Callback.class));
  final CompletionStage<com.spotify.apollo.Response<ByteString>> response =
      client.send(com.spotify.apollo.Request.forUri(URI, "GET").withTtl(Duration.ofMillis(100)));
  verify(okHttpClient).setReadTimeout(100, TimeUnit.MILLISECONDS);
  assertTrue(response.toCompletableFuture().isCompletedExceptionally());
}
项目:Library-Token-Automation    文件:LoginActivity.java   
Call post(Callback callback) throws IOException {
    OkHttpClient client = getUnsafeOkHttpClient();
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    client.setCookieHandler(cookieManager);
    RequestBody requestBody = new FormEncodingBuilder()
            .add("user_id", NetId)
            .add("user_password", password)
            .build();
    Request request = new Request.Builder()
            .url("https://studentmaintenance.webapps.snu.edu.in/students/public/studentslist/studentslist/loginauth")
            .post(requestBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
项目:aptoide-client    文件:AptoideUtils.java   
public static void startParse(final String storeName, final Context context, final SpiceManager spiceManager) {
    Toast.makeText(context, AptoideUtils.StringUtils.getFormattedString(context, R.string.subscribing, storeName), Toast.LENGTH_SHORT).show();

    GetSimpleStoreRequest request = new GetSimpleStoreRequest();
    request.store_name = storeName;

    CheckSimpleStoreListener checkStoreListener = new CheckSimpleStoreListener();
    checkStoreListener.callback = new CheckSimpleStoreListener.Callback() {
        @Override
        public void onSuccess() {
            addStoreOnCloud(storeName, context, spiceManager);
        }
    };

    spiceManager.execute(request, checkStoreListener);
}
项目:aptoide-client    文件:AptoideUtils.java   
/**
 * Execute a simple request (knock at the door) to the given URL.
 * @param url
 */
public static void knock(String url) {
    OkHttpClient client = new OkHttpClient();

    Request click = new Request.Builder().url(url).build();

    client.newCall(click).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
        }

        @Override
        public void onResponse(Response response) throws IOException {
        }
    });
}
项目:spring-async    文件:AggregatorService.java   
public void execute(final Task task) {
    log.info("Started task with {} urls", task.getUrls().size());
    task.start();
    for(int i = 0; i < task.getUrls().size(); i++) {
        final int index = i;
        final long time = System.currentTimeMillis();
        String url = task.getUrls().get(i);
        Request req = new Request.Builder().get().url(url).build();

        client.newCall(req).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                task.fail(index, time, request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                task.success(index, time, response);
            }
        });
    }
}
项目:popcorn-android    文件:SubtitleDownloader.java   
public void downloadSubtitle() {
    if (listenerReference == null) throw new IllegalArgumentException("listener must not null. Call setSubtitleDownloaderListener() to sets one");
    if (contextReference.get() == null) return;
    Context context = contextReference.get();
    SubsProvider.download(context, media, subtitleLanguage, new Callback() {
        @Override
        public void onFailure(Request request, IOException exception) {
            onSubtitleDownloadFailed();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            onSubtitleDownloadSuccess();
        }
    });
}
项目:cloudprovider    文件:DropboxApi.java   
/**
 * Remove the staled account and add a new one
 */
private void resetAccount() {
    logout(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

        }
    });
    // use Authenticator to update account
    mCloudProvider.removeAccount(mAccount);
    mCloudProvider.addAccount(getClass().getCanonicalName(), (Activity) mContext);
}
项目:cloudprovider    文件:OneDriveApi.java   
/**
 * Remove the staled account and add a new one
 */
private void resetAccount() {
    logout(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

        }
    });
    // use Authenticator to update account
    mCloudProvider.removeAccount(mAccount);
    mCloudProvider.addAccount(getClass().getCanonicalName(), (Activity) mContext);
}
项目:cloudprovider    文件:BoxApi.java   
/**
 * Remove the staled account and add a new one
 */
private void resetAccount() {
    logout(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

        }
    });
    // use Authenticator to update account
    mCloudProvider.removeAccount(mAccount);
    mCloudProvider.addAccount(getClass().getCanonicalName(), (Activity) mContext);
}
项目:rkt-launcher    文件:ClientTest.java   
@Test
public void shouldSendPostRequest() throws ExecutionException, InterruptedException {
  final Request request = new com.squareup.okhttp.Request.Builder()
      .url(URI)
      .method("POST", RequestBody.create(CONTENT_TYPE, "{}"))
      .build();
  when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
  doAnswer(invocation -> {
    final Callback callback = invocation.getArgument(0);
    callback.onResponse(new Response.Builder()
                            .request(request)
                            .protocol(Protocol.HTTP_1_1)
                            .code(Status.OK.code())
                            .message("OK")
                            .body(ResponseBody.create(CONTENT_TYPE, "{}"))
                            .header("foo", "bar")
                            .build());
    return Void.TYPE;
  }).when(call).enqueue(isA(Callback.class));
  final com.spotify.apollo.Response<ByteString> response =
      client.send(com.spotify.apollo.Request
                      .forUri(URI, "POST")
                      .withPayload(ByteString.of("{}".getBytes())))
          .toCompletableFuture().get();
  verify(okHttpClient, never()).setReadTimeout(anyLong(), any());

  assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload());
  assertEquals(Optional.of("bar"), response.header("foo"));
}
项目:find-client-android    文件:FindWiFiImpl.java   
AuthTask(String urlPart, String serverAddr, int method, String json, Callback callback) {
    this.urlPart = urlPart;
    this.serverAddr = serverAddr;
    this.method = method;
    this.json = json;
    this.callback = callback;
}
项目:Raffler-Android    文件:ChatActivity.java   
Call post(String url, String json, Callback callback) {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .addHeader("Authorization","key=AIzaSyAkeFnKc_r6TJSO7tm5OVnzkbni6dEk4Lw")
            .url(url)
            .post(body)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
项目:Raffler-Android    文件:ChatActivity.java   
public void sendPushNotification(String token, String title, String message){
    try {
        JSONObject jsonObject = new JSONObject();
        JSONObject notification = new JSONObject();
        notification.put("title", title);
        notification.put("body", message);
        JSONObject data = new JSONObject();
        data.put("sender_phone", sender.getPhone());
        data.put("sender_photo", sender.getPhoto());
        data.put("sender_name", sender.getName());
        jsonObject.put("notification", notification);
        jsonObject.put("data", data);
        jsonObject.put("to", token);

        post("https://fcm.googleapis.com/fcm/send", jsonObject.toString(), new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                FirebaseCrash.report(e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();
                    Log.d("Response", responseStr);
                    // Do what you want to do with the response.
                } else {
                    // Request not successful
                }
            }
        });

    } catch (JSONException ex) {
        Log.d("Exception", "JSON exception", ex);
    }
}
项目:Library-Token-Automation    文件:MainActivity.java   
Call post(String mode, String username, String password, Callback callback) throws IOException {
    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new FormEncodingBuilder()
            .add("mode", mode)
            .add("username", username + "@snu.in")
            .add("password", password)
            .build();
    Request request = new Request.Builder()
            .url("http://192.168.50.1/24online/servlet/E24onlineHTTPClient")
            .post(formBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
项目:Android-nRF-Beacon-for-Eddystone    文件:AuthTaskUrlShortener.java   
public AuthTaskUrlShortener(final Callback mCallBack, final String longUrl, Activity context, Account account, JSONObject jsonObject, String requestType){
    this.mOkHttpClient = new OkHttpClient();
    this.mCallBack = mCallBack;
    this.longUrl = longUrl;
    this.mActivity = context;
    this.mAccount = account;
    this.mJsonObject = jsonObject;
    this.mRequestType = requestType;
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ListProjectsTask.java   
public ListProjectsTask(Context context, String url, Callback callback, String token) {
    this.mContext = context;
    this.url = url;
    this.callback = callback;
    httpClient = new OkHttpClient();
    this.mToken = token;
}
项目:Android-nRF-Beacon-for-Eddystone    文件:RefreshAccessTokenTask.java   
public RefreshAccessTokenTask(final Callback mCallBack, final String mRefreshToken, String clientId, String code){
    this.mOkHttpClient = new OkHttpClient();
    this.mCallBack = mCallBack;
    this.mRefreshToken = mRefreshToken;
    this.mClientId = clientId;
    this.mCode = code;
}
项目:Android-nRF-Beacon-for-Eddystone    文件:RequestAccessTokenTask.java   
public RequestAccessTokenTask(final Activity activity, final Callback mCallBack, final String url, String clientId, String code){
    this.mActivity = activity;
    this.mOkHttpClient = new OkHttpClient();
    this.mCallBack = mCallBack;
    this.url = url;
    this.mClientId = clientId;
    this.mCode = code;
}
项目:Mobile-Office    文件:OkHttpClientManager.java   
private void _asynUpload(Request request, Callback callBack, IUploadCallBack uploadcallBack) {
    RequestBody body = null;
    if ((body = request.body()) != null) {
        RequestBody newBody = ProgressHelper.addProgressRequestListener(body, uploadcallBack);
        request = request.newBuilder().post(newBody).build();
    }
    mOkHttpClient.newCall(request).enqueue(callBack);
}
项目:BeeksBeacon    文件:ManageBeaconFragment.java   
private Button createAttachmentDeleteButton(final int viewId, final String attachmentName) {
    final Button button = new Button(getActivity());
    button.setLayoutParams(BUTTON_COL_LAYOUT);
    button.setText("-");
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.setEnabledViews(false, button);
            Callback deleteAttachmentCallback = new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    logErrorAndToast("Failed request: " + request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    if (response.isSuccessful()) {
                        attachmentsTable.removeView(attachmentsTable.findViewById(viewId));
                    } else {
                        String body = response.body().string();
                        logErrorAndToast("Unsuccessful deleteAttachment request: " + body);
                    }
                }
            };
            client.deleteAttachment(deleteAttachmentCallback, attachmentName);
        }
    });
    return button;
}
项目:find-client-android    文件:FindWiFiImpl.java   
AuthTask(String urlPart, String serverAddr, int method, String json, Callback callback) {
    this.urlPart = urlPart;
    this.serverAddr = serverAddr;
    this.method = method;
    this.json = json;
    this.callback = callback;
}
项目:spring4-understanding    文件:OkHttpClientHttpRequest.java   
public OkHttpListenableFuture(Call call) {
     this.call = call;
     this.call.enqueue(new Callback() {
@Override
      public void onResponse(Response response) {
       set(new OkHttpClientHttpResponse(response));
      }
      @Override
      public void onFailure(Request request, IOException ex) {
       setException(ex);
      }
     });
 }
项目:cloudprovider    文件:DropboxApi.java   
@Override
public void logout(@NonNull Callback callback) {
    RequestBody body = new FormEncodingBuilder()
            .add("client_id", CLIENT_ID)
            .add("client_secret", CLIENT_SECRET)
            .add("token", mAccessToken)
            .build();

    Request request = new Request.Builder()
            .url(REVOKE_URL)
            .post(body)
            .build();

    mHttpClient.newCall(request).enqueue(callback);
}
项目:cloudprovider    文件:CloudDriveApi.java   
@Override
public void logout(@NonNull Callback callback) {
    RequestBody body = new FormEncodingBuilder()
            .add("client_id", CLIENT_ID)
            .add("client_secret", CLIENT_SECRET)
            .add("token", mAccessToken)
            .build();

    Request request = new Request.Builder()
            .url(REVOKE_URL)
            .post(body)
            .build();

    mHttpClient.newCall(request).enqueue(callback);
}
项目:cloudprovider    文件:OneDriveApi.java   
@Override
public void logout(@NonNull Callback callback) {
    RequestBody body = new FormEncodingBuilder()
            .add("client_id", CLIENT_ID)
            .add("client_secret", CLIENT_SECRET)
            .add("token", mAccessToken)
            .build();

    Request request = new Request.Builder()
            .url(REVOKE_URL)
            .post(body)
            .build();

    mHttpClient.newCall(request).enqueue(callback);
}
项目:cloudprovider    文件:BoxApi.java   
@Override
public synchronized void logout(@NonNull Callback callback) {
    RequestBody body = new FormEncodingBuilder()
            .add("client_id", CLIENT_ID)
            .add("client_secret", CLIENT_SECRET)
            .add("token", mAccessToken)
            .build();

    Request request = new Request.Builder()
            .url(REVOKE_URL)
            .post(body)
            .build();

    mHttpClient.newCall(request).enqueue(callback);
}
项目:find-client-android    文件:FindWiFiImpl.java   
@Override
public void findTrack(Callback callback, String serverAddr, JSONObject requestBody) {
    new AuthTask("track", serverAddr, POST, requestBody.toString(), callback).execute();
}
项目:find-client-android    文件:FindWiFiImpl.java   
@Override
public void findLearn(Callback callback, String serverAddr, JSONObject requestBody) {
    new AuthTask("learn", serverAddr, POST, requestBody.toString(), callback).execute();
}
项目:find-client-android    文件:HttpCallback.java   
public HttpCallback(com.squareup.okhttp.Callback delegate) {
    this.delegate = delegate;
    this.handler = new Handler(Looper.getMainLooper());
}
项目:Library-Token-Automation    文件:LoginActivity.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_login);

    sharedPreferences = getSharedPreferences("MYPREFERENCES", Context.MODE_PRIVATE);
    NetId = sharedPreferences.getString("username", null);
    password = sharedPreferences.getString("password", null);

    if(NetId != null && password != null){
        Intent startMain = new Intent(getApplicationContext(), Details.class);
        startMain.putExtra("username", NetId);
        startMain.putExtra("password", password);
        startActivity(startMain);
}

    setContentView(R.layout.login);

    etNetId = (EditText) findViewById(R.id.email);
    etPass = (EditText) findViewById(R.id.password);
    Button btLogin = (Button) findViewById(R.id.email_sign_in_button);

    btLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NetId = etNetId.getText().toString();
            password = etPass.getText().toString();
            if(isValid()) {
                confirmDetails();
            }
        }
    });

    handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                etNetId.setError("Invalid NetId");
                Toast.makeText(LoginActivity.this, "Please check your NetID and password", Toast.LENGTH_SHORT).show();
            }
            else if (msg.what == 2) {
                etPass.setError("Invalid password");
                Toast.makeText(LoginActivity.this, "Please check your NetID and password", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });

    TextView tvCredit = (TextView) findViewById(R.id.textView2);
    //tvCredit.setText(Html.fromHtml(getString(R.string.credit)));
    tvCredit.setMovementMethod(LinkMovementMethod.getInstance());

}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void getForObserved(Callback callback, JSONObject requestBody, String apiKey) {
  // The authorization step here isn't strictly necessary. The API key is enough.
  new AuthTask("beaconinfo:getforobserved?key=" + apiKey, POST, requestBody.toString(), callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void activateBeacon(Callback callback, String beaconName) {
  new AuthTask(beaconName + ":activate", POST, "", callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void deactivateBeacon(Callback callback, String beaconName) {
  new AuthTask(beaconName + ":deactivate", POST, "", callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void decommissionBeacon(Callback callback, String beaconName) {
  new AuthTask(beaconName + ":decommission", POST, "", callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void getBeacon(Callback callback, String beaconName) {
  new AuthTask(beaconName, callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void listBeacons(Callback callback, String query) {
  new AuthTask("beacons" + "?q=" + query, callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void registerBeacon(Callback callback, JSONObject requestBody) {
  new AuthTask("beacons:register?projectId=" + mProject.getProjectId(), POST, requestBody.toString(), callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void updateBeacon(Callback callback, String beaconName, JSONObject requestBody) {
  new AuthTask(beaconName, PUT, requestBody.toString(), callback).execute();
}
项目:Android-nRF-Beacon-for-Eddystone    文件:ProximityBeaconImpl.java   
@Override
public void batchDeleteAttachments(Callback callback, String beaconName) {
  new AuthTask(beaconName + "/attachments:batchDelete?projectId=" + mProject.getProjectId(), POST, "", callback).execute();
}