i already found out how to post something to a wall with the graph api on behalf of the facebook user. But now i want to post something in the name of my application.
Here is how i'm trying to do this:
protected void btn_submit_Click(object sender, EventArgs e)
{
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("message", "Testing");
// i'll add more data later here (picture, link, ...)
data.Add("access_token", FbGraphApi.getAppToken());
FbGraphApi.postOnWall(ConfigSettings.getFbPageId(), data);
}
FbGraphApi.getAppToken()
// ...
private static string graphUrl = "https://graph.facebook.com";
//...
public static string getAppToken() {
MyWebRequest req = new MyWebRequest(graphUrl + "/" + "oauth/access_token?type=client_cred&client_id=" + ConfigSettings.getAppID() + "&client_secret=" + ConfigSettings.getAppSecret(), "GET");
return req.GetResponse().Split('=')[1];
}
FbGraphApi.postOnWall()
public static void postOnWall(string id, Dictionary<string,string> args)
{
call(id, "feed", args);
}
FbGraphApi.call()
private static void call(string id, string method, Dictionary<string,string> args )
{
string data = "";
foreach (KeyValuePair<string, string> arg in args)
{
data += arg.Key + "=" + arg.Value + "&";
}
MyWebRequest req = new MyWebRequest(graphUrl +"/" + id + "/" + method, "POST", data.Substring(0, data.Length - 1));
req.GetResponse(); // here i get: "The remote server returned an error: (403) Forbidden."
}
Does anyone see where this i going wrong? I'm really stuck on this.
Thanks!
You need to obtain the Auth Token for your application to post as that application.
The Auth_Token defines the security context you are posting as.
You would need to request the following Graph API URL, for the current user, to find the access token for your application.
https://graph.facebook.com/me/accounts?access_token=XXXXXXXX
This should give you an output similar to the following:
{
"data": [
{
"name": "My App",
"category": "Application",
"id": "10258853",
"access_token": "xxxxxxxxxxxxxxxx"
}
]
}
Be sure you have the manage_pages permission before calling that API or your will not get the access token back.
Once you have the Access Token you publish to the wall like you would any other user. Note that the ID used in the URL matches the ID of the application. This will post to the Application's wall as the Application.
https://graph.facebook.com/10258853/feed?access_token=XXXXXXX
Be sure you have the publish_stream permission as well before posting to the wall.
Recently I had worked With FB api's.
I had Done every thing in javascript.
Here is what i used to post to a users wall.
I hope this helps you.
Include the javascript library provided by FB and add your app id to it.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
For login , i used a button with "fb_login" as id and then i used jquery as follows:
$("#fb_login").click(function(){
FB.login(function(response) {
if (response.session)
{
if (response.perms)
{
// alert("Logged in and permission granted for posting");
}
else
{
// alert("Logged in but permission not granted for posting");
}
}
else
{
//alert("Not Logged In");
}
}, {perms:'publish_stream'});
Note that You have to add {perms:'publish_stream'} as done above which will obtain you the rights to post to the users wall.
A button with id="stream_publish" and then the following jquery:
$("#stream_publish").click(function(){
FB.getLoginStatus(function(response){
if(response.session)
{
publishPost(response.session);
}
});
});
function publishPost(session)
{
var publish = {
method: 'stream.publish',
message: 'Your Message',
picture : 'Image to be displayed',
link : 'The link that will be the part of the post, which can point to either your app page or your personal page or any other page',
name: 'Name or title of the post',
caption: 'Caption of the Post',
description: 'It is fun to write Facebook App!',
actions : { name : 'Start Learning', link : 'link to the app'}
};
FB.api('/me/feed', 'POST', publish, function(response) {
document.getElementById('confirmMsg').innerHTML =
'A post had just been published into the stream on your wall.';
});
};
private class FbWebViewClient extends WebViewClient {
boolean started=false;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("Facebook-WebView", "Redirect URL: " + url);
if (url.startsWith(Facebook.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
if (error == null) {
mListener.onComplete(values);
} else if (error.equals("access_denied")
|| error.equals("OAuthAccessDeniedException")) {
mListener.onCancel();
} else {
mListener.onFacebookError(new FacebookError(error));
}
FbDialog.this.dismiss();
return true;
} else if (url.startsWith(Facebook.CANCEL_URI)) {
mListener.onCancel();
FbDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_STRING)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(new DialogError(description, errorCode,
failingUrl));
FbDialog.this.dismiss();
}
public Map<String, String> getUrlParameters(String url)
throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String pair[] = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
params.put(key, value);
}
}
return params;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("Facebook-WebView", "Webview loading URL: " + url);
String newUrl="http://www.facebook.com/dialog/feed?_path=feed&app_id=";
if (url.contains("touch") && started==false) {
started=true;
ChildTabBibleLessonActivity.fbMaterial=ChildTabBibleLessonActivity.fbMaterial.replace(" ", "+");
url=url+"&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg&description="+ChildTabBibleLessonActivity.fbMaterial;
/* Map<String,String> param;
try {
param = getUrlParameters(url);
newUrl=newUrl+param.get("app_id")+"&redirect_uri="+"https://deep-rain-6015.herokuapp.com"+"&display=page&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg"+"&name=MiniBible&description=heregoesMyMessage";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
view.loadUrl(url);
//super.onPageStarted(view, url, favicon);
}
else
{
super.onPageStarted(view, url, favicon);
}
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mSpinner.dismiss();
/*
* Once webview is fully loaded, set the mContent background to be
* transparent and make visible the 'x' image.
*/
mContent.setBackgroundColor(Color.TRANSPARENT);
mWebView.setVisibility(View.VISIBLE);
mCrossImage.setVisibility(View.VISIBLE);
}
}
Related
I am developing an Android security app and have decided to implement the PlayIntegrity API as an alternative to SafetyNet API. I have already completed the necessary setup steps such as enabling the Play and Cloud console, however, I am encountering an issue where I am getting an error 'GOOGLE SERVER UNAVAILABLE' when trying to obtain a token. Can anyone provide any insight into why this might be happening and possible solutions? Any help would be greatly appreciated.
Please see below code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// playIntegritySetup.lol();
getToken();
}
private void getToken() {
String nonce = Base64.encodeToString(generateNonce(50).getBytes(), Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
// Create an instance of a manager.
IntegrityManager integrityManager = IntegrityManagerFactory.create(getApplicationContext());
// Request the integrity token by providing a nonce.
Task<IntegrityTokenResponse> integrityTokenResponse = integrityManager.requestIntegrityToken(
IntegrityTokenRequest.builder()
.setNonce(nonce)
.build());
integrityTokenResponse.addOnSuccessListener(new OnSuccessListener<IntegrityTokenResponse>() {
#Override
public void onSuccess(IntegrityTokenResponse integrityTokenResponse) {
String integrityToken = integrityTokenResponse.token();
SplashActivity.this.doIntegrityCheck(integrityToken);
Log.e("Integrity Token", "integrity token from the app" + integrityToken);
}
});
integrityTokenResponse.addOnFailureListener(e -> showErrorDialog("Error getting token from Google. Google said: " + getErrorText(e)));
}
private void doIntegrityCheck(String token) {
AtomicBoolean hasError = new AtomicBoolean(false);
Observable.fromCallable(() -> {
OkHttpClient okHttpClient = new OkHttpClient();
Response response = okHttpClient.newCall(new Request.Builder().url("money control url" + "token from backend server" + token).build()).execute();
Log.e("Token", "token from the app" + token);
if (!response.isSuccessful()) {
hasError.set(true);
return "Api request error. Code: " + response.code();
}
ResponseBody responseBody = response.body();
if (responseBody == null) {
hasError.set(true);
return "Api request error. Empty response";
}
JSONObject responseJson = new JSONObject(responseBody.string());
if (responseJson.has("error")) {
hasError.set(true);
return "Api request error: " + responseJson.getString("error");
}
if (!responseJson.has("deviceIntegrity")) {
hasError.set(true);
}
return responseJson.getJSONObject("deviceIntegrity").toString();
}) // Execute in IO thread, i.e. background thread.
.subscribeOn(Schedulers.io())
// report or post the result to main thread.
.observeOn(AndroidSchedulers.mainThread())
// execute this RxJava
.subscribe(new Observer<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(String result) {
if (hasError.get()) {
if (result.contains("MEETS_DEVICE_INTEGRITY") && result.contains("MEETS_BASIC_INTEGRITY")) {
//Here goes my other code
}
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
});
}
private String getErrorText(Exception e) {
String msg = e.getMessage();
if (msg == null) {
return "Unknown Error";
}
//the error code
int errorCode = Integer.parseInt(msg.replaceAll("\n", "").replaceAll(":(.*)", ""));
switch (errorCode) {
case IntegrityErrorCode.API_NOT_AVAILABLE:
return "API_NOT_AVAILABLE";
case IntegrityErrorCode.NO_ERROR:
return "NO_ERROR";
case IntegrityErrorCode.INTERNAL_ERROR:
return "INTERNAL_ERROR";
case IntegrityErrorCode.NETWORK_ERROR:
return "NETWORK_ERROR";
case IntegrityErrorCode.PLAY_STORE_NOT_FOUND:
return "PLAY_STORE_NOT_FOUND";
case IntegrityErrorCode.PLAY_STORE_ACCOUNT_NOT_FOUND:
return "PLAY_STORE_ACCOUNT_NOT_FOUND";
case IntegrityErrorCode.APP_NOT_INSTALLED:
return "APP_NOT_INSTALLED";
case IntegrityErrorCode.PLAY_SERVICES_NOT_FOUND:
return "PLAY_SERVICES_NOT_FOUND";
case IntegrityErrorCode.APP_UID_MISMATCH:
return "APP_UID_MISMATCH";
case IntegrityErrorCode.TOO_MANY_REQUESTS:
return "TOO_MANY_REQUESTS";
case IntegrityErrorCode.CANNOT_BIND_TO_SERVICE:
return "CANNOT_BIND_TO_SERVICE";
case IntegrityErrorCode.NONCE_TOO_SHORT:
return "NONCE_TOO_SHORT";
case IntegrityErrorCode.NONCE_TOO_LONG:
return "NONCE_TOO_LONG";
case IntegrityErrorCode.GOOGLE_SERVER_UNAVAILABLE:
return "GOOGLE_SERVER_UNAVAILABLE";
case IntegrityErrorCode.NONCE_IS_NOT_BASE64:
return "NONCE_IS_NOT_BASE64";
default:
return "Unknown Error";
}
}
private String generateNonce(int length) {
String nonce = "";
String allowed = getNonce();
for (int i = 0; i < length; i++) {
nonce = nonce.concat(String.valueOf(allowed.charAt((int) Math.floor(Math.random() * allowed.length()))));
}
return nonce;
}
public native String getNonce();
static {
System.loadLibrary("all-keys");
}
I ran into the same problem and I found a solution for this.
You need to specify cloudProjectNumber() when you are working on outside of Google Play, which can be found in google cloud console.
Quote from the doc:
Important: In order to receive and decrypt Integrity API responses,
apps not available on Google Play need to include their Cloud project
number in their requests. You can find this in Project info in the
Google Cloud Console.
So the code should be like this:
IntegrityTokenRequest.builder()
.setNonce(nonce)
.cloudProjectNumber(100004676) // your cloud project number here for dev build
.build());
View model has been initialized by the following code inside fragment.
viewModel.getContacts(pageNumber, AppConstants.DIRECTION).observe(getActivity(), list -> {
adapter.submitList(list);
});
where viewModel.getContacts() method calls a repository method which in turn makes the web request and brings the response back.
public MutableLiveData<List<Contact>> getAllContacts(int page, String sortedBy) {
return repository.getAllContacts(page, sortedBy);
}
where repository.getAllContacts() method is
public MutableLiveData<List<Contact>> getAllContacts(int page, String orderBy) {
if (allContacts == null) {
allContacts = new MutableLiveData<>();
}
//we will load it asynchronously from server in this method
loadContacts(page, orderBy);
return allContacts;
}
private void loadContacts(int page, String orderBy) {
Call<ContactsResponse> call = bearerApiInterface.getContacts(page, orderBy);
call.enqueue(new Callback<ContactsResponse>() {
#Override
public void onResponse(Call<ContactsResponse> call, Response<ContactsResponse> response) {
Timber.e("Contacts Response => " + new GsonBuilder().setPrettyPrinting().create().toJson(response.body()));
//finally we are setting the list to our MutableLiveData
allContacts.setValue(response.body().getResult().getData());
}
#Override
public void onFailure(Call<ContactsResponse> call, Throwable t) {
}
});
}
And here is my recycler view scroll listener
recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
loadNextPage();
}
});
Upon scrolling when loadNextPage() gets called, how viewModel.getContacts() could be triggered from loadNextPage() method.
What are the options to send the call again with incremented page number and observe it with same viewModel.getContacts() method. Paging list adapter is not an option for now as the response needs to be updated, deleted & customized while paging list adapter isn't doing that without datasource and snapshot inclusion which isn't working (any help with that would be very helpful if it is possible).
And below is the code for deleting any item from recycler view.
#Override
public void onItemDelete(RecyclerView.ViewHolder viewHolder, int position) {
mActivity.showProgressBar(true);
Timber.e("Delete the contact at position " + position);
viewModel.deleteContact(adapter.getContactAt(viewHolder.getAdapterPosition()).getId(), adapter.getContactAt(viewHolder.getAdapterPosition())).observe(this, new Observer<Boolean>() {
#Override
public void onChanged(Boolean isSuccess) {
if (isSuccess) {
mActivity.showErrorDialog("Contact Deleted Successfully", null, null);
listAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
} else {
mActivity.showErrorDialog("Something went wrong, please try again", null, null);
}
}
});
}
The view model delete method is
public MutableLiveData<Boolean> deleteContact(int id, Contact contact) {
return repository.deleteThisContact(id, contact);
}
And the repository delete method is
public MutableLiveData<Boolean> deleteThisContact(int contactId, Contact contact) {
if (deleteContact == null)
deleteContact = new MutableLiveData<>();
callDeleteContact(contactId, contact);
return deleteContact;
}
private void callDeleteContact(int contactId, Contact contact) {
Call<JsonObject> call = bearerApiInterface.deleteContact(contactId);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.isSuccessful() && response.code() == 200) {
Timber.e("***** Contact Deleted Successfully => " + new GsonBuilder().setPrettyPrinting().create().toJson(response.body()));
delete(contact);
deleteContact.setValue(true);
} else {
try {
deleteContact.setValue(false);
String errorMessage = new APIError().extractMessage(new JSONObject(response.errorBody() != null ? response.errorBody().string().trim() : null));
Timber.e("***** Error message is => " + errorMessage);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
deleteContact.setValue(false);
Timber.e("***** onFailure" + "response: " + t.getMessage());
}
});
}
Any related code which might be worthy of sharing can be asked. Skipped for simplicity.
You will need to implement the android paging:
First, you have to add on gradle the paging lib:
implementation 'androidx.paging:paging-runtime:2.1.0'
Your data source must extend the PageKeyedDataSource, so, you have to implement 3 methods, loadInitial, loadAfter and loadBefore
On your view model you must create a pager config variable, like:
private val config: PagedList.Config = PagedList.Config.Builder()
.setPageSize(PAGE_SIZE)
.setInitialLoadSizeHint(PAGE_SIZE_HINT)
.setEnablePlaceholders(false)
.build()
It will set up how the pager must be executed, and do you have to create an executor to load the data:
private val executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE)
And after all, create a livedata to receive the list:
val your_source: LiveData<PagedList<YourSource>> = LivePagedListBuilder(dataFactory, config)
.setFetchExecutor(executor)
.build()
Your recycler view adapter must be changed to a PagedListAdapter instead.
I recommend this article:
https://androidwave.com/pagination-in-recyclerview/
I have build a hybrid-app using flutter's web_view_plugin(webview).
One of our paying methods require to open a 3rd party app(in this case kakaotalk). But the flutter webview plugin does not provide this function and returned net::ERR_UNKNOWN_URL_SCHEME. I did some research and I understand that the problem lies in the url. If the url does not start with http or https, it will cause this error.
So, to solve this problem I had to change native java code. Now I have no experience at all with java and android, so fixing the native code was very difficult. I understand that I have to modify shouldOverrideUrlLoading part, in order to allow the url that starts with intent:// and also I have to put in some validation to check if the app is installed or not.(If not installed the user should be redirected to playstore)
The code which I added is in shouldOverrideUrlLoading.
I also did three imports. The rest is code, generated by flutter
package com.flutter_webview_plugin;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Intent; //added import
import android.net.Uri; //added import
import android.content.ActivityNotFoundException; //added import
/**
* Created by lejard_h on 20/12/2017.
*/
public class BrowserClient extends WebViewClient {
private Pattern invalidUrlPattern = null;
public BrowserClient() {
this(null);
}
public BrowserClient(String invalidUrlRegex) {
super();
if (invalidUrlRegex != null) {
invalidUrlPattern = Pattern.compile(invalidUrlRegex);
}
}
public void updateInvalidUrlRegex(String invalidUrlRegex) {
if (invalidUrlRegex != null) {
invalidUrlPattern = Pattern.compile(invalidUrlRegex);
} else {
invalidUrlPattern = null;
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Map<String, Object> data = new HashMap<>();
data.put("url", url);
data.put("type", "startLoad");
FlutterWebviewPlugin.channel.invokeMethod("onState", data);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Map<String, Object> data = new HashMap<>();
data.put("url", url);
FlutterWebviewPlugin.channel.invokeMethod("onUrlChanged", data);
data.put("type", "finishLoad");
FlutterWebviewPlugin.channel.invokeMethod("onState", data);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
// returning true causes the current WebView to abort loading the URL,
// while returning false causes the WebView to continue loading the URL as usual.
String url = request.getUrl().toString();
boolean isInvalid = checkInvalidUrl(url);
Map<String, Object> data = new HashMap<>();
data.put("url", url);
data.put("type", isInvalid ? "abortLoad" : "shouldStart");
FlutterWebviewPlugin.channel.invokeMethod("onState", data);
return isInvalid;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// returning true causes the current WebView to abort loading the URL,
// while returning false causes the WebView to continue loading the URL as usual.
if (url.startsWith(INTENT_PROTOCOL_START)) {
final int customUrlStartIndex = INTENT_PROTOCOL_START.length();
final int customUrlEndIndex = url.indexOf(INTENT_PROTOCOL_INTENT);
if (customUrlEndIndex < 0) {
return false;
} else {
final String customUrl = url.substring(customUrlStartIndex, customUrlEndIndex);
try {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(customUrl)));
} catch (ActivityNotFoundException e) {
final int packageStartIndex = customUrlEndIndex + INTENT_PROTOCOL_INTENT.length();
final int packageEndIndex = url.indexOf(INTENT_PROTOCOL_END);
final String packageName = url.substring(packageStartIndex, packageEndIndex < 0 ? url.length() : packageEndIndex);
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_STORE_PREFIX + packageName)));
}
return true;
}
} else {
return false;
}
// boolean isInvalid = checkInvalidUrl(url);
// Map<String, Object> data = new HashMap<>();
// data.put("url", url);
// data.put("type", isInvalid ? "abortLoad" : "shouldStart");
// FlutterWebviewPlugin.channel.invokeMethod("onState", data);
// return isInvalid;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
Map<String, Object> data = new HashMap<>();
data.put("url", request.getUrl().toString());
data.put("code", Integer.toString(errorResponse.getStatusCode()));
FlutterWebviewPlugin.channel.invokeMethod("onHttpError", data);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Map<String, Object> data = new HashMap<>();
data.put("url", failingUrl);
data.put("code", errorCode);
FlutterWebviewPlugin.channel.invokeMethod("onHttpError", data);
}
private boolean checkInvalidUrl(String url) {
if (invalidUrlPattern == null) {
return false;
} else {
Matcher matcher = invalidUrlPattern.matcher(url);
return matcher.lookingAt();
}
}
}
The code compiles, but it still returns the same error net::ERR_UNKNOWN_URL_SCHEME when I try to pay with the "3rd party app(kakaotalk)"
I encountered a similar error on Android before when Firebase Dynamic Links are being forced to be loaded in a WebView. In my case, FDL is expected to be handled by Google Play Services in Android. But since the WebView doesn't know what to do with the link it's forced to display, the WebView returns "net::ERR_UNKNOWN_URL_SCHEME" error. I'm unsure if this is the same case as yours since I'm unable to verify the link that you're trying to load apart from "intent://kakaopay..."
You can try opening the link externally by using url_launcher. Use RegEx to filter intent URLs and check if the URL can be launched and be handled externally (outside the app).
var yourURL = "URL goes here";
// Check if URL contains "intent"
yourURL.contains(RegExp('^intent://.*\$')){
// Check if the URL can be launched
if (await canLaunch(yourURL)) {
await launch(yourURL);
} else {
print('Could not launch $yourURL');
}
}
Also, the plugin (web_view_plugin) that you're using seems to be outdated, and I can't find it here https://pub.dev/packages?q=web_view_plugin. Flutter has its official WebView plugin (webview_flutter) that has been released and I suggest checking it out if it fits your use case.
Listen, In some cases using #omatt's answer might not work, especially for webview_flutter. I struggled to find a solution so I did this:
_launchURL(url) async {
var link = "https://hiddenwords.page.link/deposit";
if (await canLaunch(link)) {
await launch(link,
forceWebView: false, enableJavaScript: true, forceSafariVC:
false);
} else {
throw 'Could not launch $link';
}
}
I manually put the url/link I wanted it to open in the _launch function... Dont mind the url in the _launch parenthesis.
I also added this to the Webview widget:
navigationDelegate: (NavigationRequest request) {
if (request.url.contains(RegExp('^intent://.*\$'))) {
_launchURL(request.url);
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
Hope this works for you. It works for me...
1.Use your APP open other app in flutter with parameter(in your dynamic link);
2.use: url_launcher: ^6.1.6;
First, their app must support dynamic link;
Second, they provide you with dynamic links for their deals;
In this way, we can click the dynamic link in your APP and jump to the specified page of their APP.
Code:
final Uri toLaunch = Uri(scheme: 'https', host: 'link.fitstop.com', path: 'link/qbvQ/');
//https://link.fitstop.com/link/qbvQ is dynamic link
Future<void>? _launched;
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchInBrowser(toLaunch);
}),
child: Text(
'url_launcher',
),
)
Future<void> _launchInBrowser(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.externalApplication,
)) {
throw 'Could not launch $url';
}
}
I am trying to save a new document to MongoDB using the Vertx MongoClient as follows:
MongoDBConnection.mongoClient.save("booking", query, res -> {
if(res.succeeded()) {
documentID = res.result();
System.out.println("MongoDB inserted successfully. + document ID is : " + documentID);
}
else {
System.out.println("MongoDB insertion failed.");
}
});
if(documentID != null) {
// MongoDB document insertion successful. Reply with a booking ID
String resMsg = "A confirmed booking has been successfully created with booking id as " + documentID +
". An email has also been triggered to the shared email id " + emailID;
documentID = null;
return new JsonObject().put("fulfillmentText", resMsg);
}
else {
// return intent response
documentID = null;
return new JsonObject().put("fulfillmentText",
"There is some issues while booking the shipment. Please start afreash.");
}
The above code successfully writes the query jsonObject to MongoDB collection booking. However, the function which contains this code always returns with There is some issues while booking the shipment. Please start afreash.
This is happening probably because the MongoClient save() handler "res" is asynchronous. But, I want to return conditional responses based on successful save() operation and on failed save operation.
How to achieve it in Vertx Java?
Your assumption is correct, you dont wait for the async response from the database. What you can do, is to wrap it in a Future like this:
public Future<JsonObject> save() {
Future<JsonObject> future = Future.future();
MongoDBConnection.mongoClient.save("booking", query, res -> {
if(res.succeeded()) {
documentID = res.result();
if(documentID != null) {
System.out.println("MongoDB inserted successfully. + document ID is : " + documentID);
String resMsg = "A confirmed booking has been successfully created with booking id as " + documentID +
". An email has also been triggered to the shared email id " + emailID;
future.complete(new JsonObject().put("fulfillmentText", resMsg));
}else{
future.complete(new JsonObject().put("fulfillmentText",
"There is some issues while booking the shipment. Please start afreash."))
}
} else {
System.out.println("MongoDB insertion failed.");
future.fail(res.cause());
}
});
return future;
}
Then i assume you have and endpoint that eventually calls this, eg:
router.route("/book").handler(this::addBooking);
... then you can call the save method and serve a different response based on the result
public void addBooking(RoutingContext ctx){
save().setHandler(h -> {
if(h.succeeded()){
ctx.response().end(h.result());
}else{
ctx.response().setStatusCode(500).end(h.cause());
}
})
}
You can use RxJava 2 and a reactive Mongo Client (io.vertx.reactivex.ext.mongo.MongoClient)
Here is a code snippet:
Deployer
public class Deployer extends AbstractVerticle {
private static final Logger logger = getLogger(Deployer.class);
#Override
public void start(Future<Void> startFuture) {
DeploymentOptions options = new DeploymentOptions().setConfig(config());
JsonObject mongoConfig = new JsonObject()
.put("connection_string",
String.format("mongodb://%s:%s#%s:%d/%s",
config().getString("mongodb.username"),
config().getString("mongodb.password"),
config().getString("mongodb.host"),
config().getInteger("mongodb.port"),
config().getString("mongodb.database.name")));
MongoClient client = MongoClient.createShared(vertx, mongoConfig);
RxHelper.deployVerticle(vertx, new BookingsStorage(client), options)
.subscribe(e -> {
logger.info("Successfully Deployed");
startFuture.complete();
}, error -> {
logger.error("Failed to Deployed", error);
startFuture.fail(error);
});
}
}
BookingsStorage
public class BookingsStorage extends AbstractVerticle {
private MongoClient mongoClient;
public BookingsStorage(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
#Override
public void start() {
var eventBus = vertx.eventBus();
eventBus.consumer("GET_ALL_BOOKINGS_ADDRESS", this::getAllBookings);
}
private void getAllBookings(Message msg) {
mongoClient.rxFindWithOptions("GET_ALL_BOOKINGS_COLLECTION", new JsonObject(), sortByDate())
.subscribe(bookings -> {
// do something with bookings
msg.reply(bookings);
},
error -> {
fail(msg, error);
}
);
}
private void fail(Message msg, Throwable error) {
msg.fail(500, "An unexpected error occurred: " + error.getMessage());
}
private FindOptions sortByDate() {
return new FindOptions().setSort(new JsonObject().put("date", 1));
}
}
HttpRouterVerticle
// inside a router handler:
vertx.eventBus().rxSend("GET_ALL_BOOKINGS_ADDRESS", new JsonObject())
.subscribe(bookings -> {
// do something with bookings
},
e -> {
// handle error
});
How to create HTTP post connection to multiple URLs and post the JSON data to get the response from all the URLs using parallel.io in JAVA. I have tried with the below code set. But getting 404/java.net.ConnectException: http error
public class ParallecService {
private ParallelClient parallelClient;
private List<String> postHostsList = Arrays.asList("http://www.url1.com", "http://www.url2.com", "http://www.url3.com");
public void processRequest() {
parallelClient = new ParallelClient();
}
public void processPostRequests() {
parallelClient = new ParallelClient();
String requestBody = "JSON DATA";
parallelClient.prepareHttpPost("").setConcurrency(20).setTargetHostsFromList(postHostsList).setHttpHeaders(new ParallecHeader().addPair("Content-Type", "application/json")).setHttpEntityBody(requestBody).execute(
new ParallecResponseHandler() {
public void onCompleted(ResponseOnSingleTask responseOnSingleTask, Map<String, Object> map) {
responseOnSingleTask.getStatusCode().replaceAll("", "_");
System.out.println("Status Code : " + responseOnSingleTask.getStatusCode());
System.out.println("Last Updated" + PcDateUtils.getNowDateTimeStrStandard());
System.out.println(responseOnSingleTask.getErrorMessage());
System.out.println(responseOnSingleTask.getStackTrace());
System.out.println(responseOnSingleTask.getError());
System.out.println(responseOnSingleTask.getRequest().getRequestContent());
}
}
);
parallelClient.releaseExternalResources();
}
}