@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")); }
@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()); }
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; }
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); }
/** * 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 { } }); }
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); } }); } }
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(); } }); }
/** * 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); }
@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")); }
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; }
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; }
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); } }
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; }
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; }
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; }
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; }
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; }
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); }
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; }
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); } }); }
@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); }
@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); }
@Override public void findTrack(Callback callback, String serverAddr, JSONObject requestBody) { new AuthTask("track", serverAddr, POST, requestBody.toString(), callback).execute(); }
@Override public void findLearn(Callback callback, String serverAddr, JSONObject requestBody) { new AuthTask("learn", serverAddr, POST, requestBody.toString(), callback).execute(); }
public HttpCallback(com.squareup.okhttp.Callback delegate) { this.delegate = delegate; this.handler = new Handler(Looper.getMainLooper()); }
@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()); }
@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(); }
@Override public void activateBeacon(Callback callback, String beaconName) { new AuthTask(beaconName + ":activate", POST, "", callback).execute(); }
@Override public void deactivateBeacon(Callback callback, String beaconName) { new AuthTask(beaconName + ":deactivate", POST, "", callback).execute(); }
@Override public void decommissionBeacon(Callback callback, String beaconName) { new AuthTask(beaconName + ":decommission", POST, "", callback).execute(); }
@Override public void getBeacon(Callback callback, String beaconName) { new AuthTask(beaconName, callback).execute(); }
@Override public void listBeacons(Callback callback, String query) { new AuthTask("beacons" + "?q=" + query, callback).execute(); }
@Override public void registerBeacon(Callback callback, JSONObject requestBody) { new AuthTask("beacons:register?projectId=" + mProject.getProjectId(), POST, requestBody.toString(), callback).execute(); }
@Override public void updateBeacon(Callback callback, String beaconName, JSONObject requestBody) { new AuthTask(beaconName, PUT, requestBody.toString(), callback).execute(); }
@Override public void batchDeleteAttachments(Callback callback, String beaconName) { new AuthTask(beaconName + "/attachments:batchDelete?projectId=" + mProject.getProjectId(), POST, "", callback).execute(); }