I got userinfo, how get user posts from wall? - java

I started work with Vkontakte android SDK, and doing it well). I made authorization, and got userFirstName, userLastName and userPhoto. But I have no idea how get user wall, or user posts from user wall. It should be similar, and I see response #2 in logcat, but I don't really know how parse it???
//Prepare request for userName and photo
final VKRequest request1 = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS, "photo_100, contacts"));
//Prepare request for userWall
final VKRequest request2 = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID));
//Parallel executing requests
VKBatchRequest batch = new VKBatchRequest(request1, request2);
batch.executeWithListener(new VKBatchRequest.VKBatchRequestListener() {
#Override
public void onComplete(VKResponse[] responses) {
super.onComplete(responses);
//Work with responses
//*****
//UserName and photo response
//*****
VKApiUserFull user = ((VKList<VKApiUserFull>) responses[0].parsedModel).get(0);
Ion.with(ivUserPhoto).placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.load(user.photo_100);
tvUserName.setText(user.first_name + " " + user.last_name);
//********
//Wall response similar sa userResponse...
//********
VKApiPost mPost = ((VKList<VKApiPost>) responses[1].parsedModel).get(0);
Log.e("post name", mPost.toString());
}
#Override
public void onError(VKError error) {
//Error;
}
});

Here right code, tnx Dreddik <-- vk android sdk developer.
VKRequest request2 = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, VKSdk.getAccessToken().userId, VKApiConst.EXTENDED, 1));
request2.executeWithListener(new VKRequestListener() {
#Override
public void onError(VKError error) {
}
#Override
public void onComplete(VKResponse response) {
VKList<VKApiPost> posts = (VKList<VKApiPost>) response.parsedModel;
VKApiPost post = posts.get(0);
Log.d("Post:", post.toString());
}
});

Related

Making Connected User with stripe android + firebase

I'm very new to working with backend server stuff and nodejs. I'm trying to set up Stripe with my app and now trying to create a Connected account with stripe. Was following this https://stripe.com/docs/connect/collect-then-transfer-guide but I don't understand enough to make it work. How do I get information from the server or send it through to make the account.
this is what I got so far
binding.connectWithStripe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String redirect = "https://www.example.com/connect-onboard-redirect";
String url = "https://connect.stripe.com/express/oauth/authorize" +
"?client_id=" + "ca_Hdth53g5sheh4w4hwhw5h4weh5" +
"&state=" + 1234 +
"&redirect_uri=" + redirect;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(view.getContext(), Uri.parse(url));
}
});
const express = require('express');
const app = express();
app.use(express.json());
const { resolve } = require("path");
const stripe = require('stripe')('sk_test_xxxx');
app.get("/", (req, res) => {
// Display landing page.
const path = resolve("./index.html");
res.sendFile(path);
});
app.get("/connect/oauth", async (req, res) => {
const { code, state } = req.query;
// Assert the state matches the state you provided in the OAuth link (optional).
if(!stateMatches(state)) {
return res.status(403).json({ error: 'Incorrect state parameter: ' + state });
}
// Send the authorization code to Stripe's API.
stripe.oauth.token({
grant_type: 'authorization_code',
code
}).then(
(response) => {
var connected_account_id = response.stripe_user_id;
saveAccountId(connected_account_id);
// Render some HTML or redirect to a different page.
return res.status(200).json({success: true});
},
(err) => {
if (err.type === 'StripeInvalidGrantError') {
return res.status(400).json({error: 'Invalid authorization code: ' + code});
} else {
return res.status(500).json({error: 'An unknown error occurred.'});
}
}
);
});
const stateMatches = (state_parameter) => {
// Load the same state value that you randomly generated for your OAuth link.
const saved_state = 'sv_53124';
return saved_state == state_parameter;
}
const saveAccountId = (id) => {
// Save the connected account ID from the response to your database.
console.log('Connected account ID: ' + id);
}
app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
The sign up page opens and can enter the test info but after submiting it's not actually creating the account in Stripe dashboard. Any help would be much appreciated
enter image description here
After you complete the Express account sign up, Stripe redirects your customer to the redirect URI you specified on your Connect OAuth url (looks like yours is https://www.example.com/connect-onboard-redirect).
You should redirect to a real page of yours here. The redirect URL will append query params containing the authorization code e.g. https://www.example.com/connect-onboard-redirect?code=ac_1234
where ac_1234 is the OAuth authorization code.
You need to parse out that authorization code and send it to your backend and complete the OAuth connection to actually connect that Express account to your Platform: https://stripe.com/docs/connect/oauth-express-accounts#token-request
Got the last piece of my puzzle. Didn't know how to communicate with nodejs and use the GET method. I used volley with this piece of code
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://10.0.2.2:4242" + "/connect/oauth",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(">>>>>>>>CONNECTED?", ">>>CONNECTED!!!<<<");
// enjoy your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(">>>>>>>>>>ERRRRRRROR", error.toString());
// enjoy your error status
}
});
queue.add(stringRequest);
Hope that helps anyone else starting to learn nodejs :)

Trying to implement RapidApi on Android Studio

I am trying to implement twinword word dictionary API on Android Studio.
The error message I got is:
I/OkHttpClient: Callback failure for call to https://twinword-twinword-bundle-v1.p.rapidapi.com/...
java.io.IOException: Unexpected code Response{protocol=http/1.1, code=403, message=Forbidden, url=https://twinword-twinword-bundle-v1.p.rapidapi.com/word_example/?entry=mask}
at com.example.anew.SentenceFramer$1.onResponse(SentenceFramer.java:58)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:177)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:760)
I believe the message is forbidden because it cannot access the rapidAPI and I think the problem is I couldn't figure out what is the Project Key as I couldn't find it anywhere in RapidAPI website. Or does the problem actually lies in my codes?
RapidApiConnect connect = new RapidApiConnect("I put my project name here", "I dont know where to find project key");
String object_1;
String host = "twinword-twinword-bundle-v1.p.rapidapi.com";
String API_KEY = "this is the api key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sentence_framer);
object_1 = getIntent().getStringExtra("First Object");
Log.d("EDMTERROR", object_1);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://twinword-twinword-bundle-v1.p.rapidapi.com/word_example/?entry=mask")
.get()
.addHeader("x-rapidapi-host", host)
.addHeader("x-rapidapi-key", API_KEY)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.d("EDMTERROR", "onfailure");
e.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
Log.d("EDMTERROR", "masalah");
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) {
Log.d("EDMTERROR", "unexpected code");
throw new IOException("Unexpected code " + response);
}
Headers responseHeaders = response.headers();
Log.d("EDMTERROR", "headers");
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
}
This is my first time doing this, so I haven't got the slightest clue on how to fix this. The website Im trying to reach is https://rapidapi.com/twinword/api/word-dictionary?endpoint=53aa5089e4b0a798dbd1a61d.
Please help, I need this for my final year project...
It's looks like you haven't subscribed to the API on rapidapi.com (https://rapidapi.com/twinword/api/word-dictionary/pricing)
also, I couldn't find the endpoint you are trying to use (/word_example), looks like the right endpoint is /example.
You can always contact them at support#rapidapi.com

Post request with basic auth in retrofit?

Using Retrofit I post my contact list on the phone without authentication. I need to do retrofit basic authentication, but as far as I can't see from the internet. Can you help me, please?
This is my Code:
public void GetContactsIntoArrayList(){
mAPIService = ApiUtils.getAPIService();
final User user = new User();
final Post post = new Post();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
int i = 0;
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
StoreContacts.add(name + " " + ":" + " " + phonenumber);
user.setphoneNumber(phonenumber.toString().trim());
user.setname(name.toString().trim());
List<User> phoneList = new ArrayList<>();
phoneList.add(user);
post.setUsers(phoneList);
sendPost(post);
}
cursor.close();
}
public void sendPost(Post post){
mAPIService.savePost(post).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
Log.d("requestError", "onResponse: "+ call.request().body().toString());
if(response.isSuccessful()) {
Log.i("Is Ok?","OK :)");
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
}
This is so far the easiest method i have ever tried for "Basic Authentication".
Use the below code to generate the auth header (API/Repository class)
var basic = Credentials.basic("YOUR_USERNAME", "YOUR_PASSWORD")
Pass this as header to the webservice call (API/Repository class)
var retrofitCall = myWebservice.getNewsFeed(basic)
Add the basic header as parameter (Retrofit Webservice interface class)
#GET("newsfeed/daily")
fun getNewsFeed(#Header("Authorization") h1:String):Call<NewsFeedResponse>
My code is in Kotlin, just in case you were looking for Java. But can be easily translated to Java.
References: https://mobikul.com/basic-authentication-retrofit-android/
You can add auth value in header of the request like if you want to send auth token then follow below step:
#POST("/auth/update-contactno")
#Headers(
"Content-Type: application/json",
Constants.headerApp,
Constants.headerLanguage,
Constants.headerPlatform,
Constants.headerVersion
)
fun updateMobileNumber(#Header(Constants.authorization) token: String?, #Body verifyForgotPasswordOTPInput: VerifyForgotPasswordOTPInput): Call<JsonObjectResponse<UserModel>>
And call updateMobileNumber() like :
apiService.updateMobileNumber(token, verifyForgotPasswordOTPInput)

Facebook graph api not sending all data in android

I'm trying to get user_id, name & email from facebook via graph API. but its not sending me the email. I'm using a function like this:
void callGraphApi() {
accessToken = AccessToken.getCurrentAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
tv_response.setText(response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
I'm only getting a response like this:
{"id":"1480750682018443","name":"Ogwemuvwem Ossas","gender":"male"}, error: null}
Any solution??
In your facebook developer dashboard Go to App review in There you can see your data request permission.
If email permission not listed there you have to add it by click start a submission button on the same page.
From facebook Docs:
Note, even if you request the email permission it is not guaranteed
you will get an email address. For example, if someone signed up for
Facebook with a phone number instead of an email address, the email
field may be empty.
You can try this new api. You can pass permissions in ArrayList like this.
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
getUserDetails(loginResult);
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
You can handle LoginResult like this.
// Get Facebook login results
protected void getUserDetails(LoginResult loginResult) {
GraphRequest data_request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json_object, GraphResponse response) {
Log.i("onfbCompleted: ", json_object.toString());
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
I Hope it's help for you. :)

Error: Unsupported Media Type (Codename One)

I'm trying to send a POST request from my CN1 app on NetBeans IDE but im getting this error each time i run the app "Error 415: Unsupported Media Type". here are my codes:
Request Code:
#Override
protected void onMain_ButtonAction(Component c, ActionEvent event) {
String name=findTextField(c).getText();
String qty=findTextField1(c).getText();
ConnectionRequest r= new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
}
};
r.setUrl("http://localhost:8080/webservicess/webresources/getreq/post");
r.setPost(true);
r.setHttpMethod("POST");
r.addArgument("name", name);
r.addArgument("quantity", qty);
NetworkManager.getInstance().addToQueueAndWait(r);
}
}
REST Service
#POST
#Path("post")
#Consumes("application/json")
public void putJson(Product product) {
String result = "Product recieved : " + product;
System.out.println(""+result);
}
}
Product.java class
class Product {
public String name;
public int quantity;
Product(){
}
}
Please check the attached picture for the screenshot of the error message.
I want a situation whereby when i click on the Submit button the value entered for product name and quantity should be displayed on the REST console. Please come to my rescue on this.
Best Regards,
Yahya-Imam Munir Kolapo
Based on POST JSON fails with 415 Unsupported media type, Spring 3 mvc
You need to set the accept request header which you can do in Codename One thru addRequestHeader:
r.addRequestHeader("accept", "application/json");
The other problem you are having is a bit misleading but I'm guessing the webservice accepts JSON in the body and not standard post arguments so this should probably work:
final String name = findTextField(c).getText();
final String qty = findTextField1(c).getText();
ConnectionRequest r= new ConnectionRequest(){
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
StringBuilder val = new StringBuilder("{\"name\":\"");
val.append(name);
val.append("\",\"quantity\":");
val.append(qty);
val.append("}");
if(shouldWriteUTFAsGetBytes()) {
os.write(val.toString().getBytes("UTF-8"));
} else {
OutputStreamWriter w = new OutputStreamWriter(os, "UTF-8");
w.write(val.toString());
}
}
#Override
protected void readResponse(InputStream input) throws IOException {
}
};
r.setUrl("http://localhost:8080/webservicess/webresources/getreq/post");
r.setPost(true);
NetworkManager.getInstance().addToQueueAndWait(r);

Categories

Resources