Hi guys I have a problem in codename one api sms
when I push the button he show me this error (error:411 length required)
btsms.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
// String myURL = "https://rest.nexmo.com/sms/json?api_key=*****&api_secret=*****&to=*****" + "&from=*****&text=*****";
String myURL = "https://rest.nexmo.com/sms/json?api_key=d5b95eee&api_secret=93a8c398b48c63bf&to=21625308299&from=NEXMO&text=reservation_annulée";
ConnectionRequest cntRqst = new ConnectionRequest() {
#Override
protected void readResponse(InputStream in) throws IOException {
}
#Override
protected void postResponse() {
Dialog.show("SMS", "sms successfully sent", "OK", null);
}
};
cntRqst.setUrl(myURL);
NetworkManager.getInstance().addToQueue(cntRqst);
}
});
Can you help me please thanks :)
Before I begin you do know there is a Twilio SMS callback library in Codename One right?
You are sending a post call with a URL that's constructed for GET. A minimal fix would be:
cntRqst.setPost(false);
However, I would personally write it as:
ConnectionRequest cntRqst = new ConnectionRequest("https://rest.nexmo.com/sms/json", false) {
// ...
};
cntRqst.addArgument("api_key", API_KEY);
cntRqst.addArgument("api_secret", API_SECRET);
cntRqst.addArgument("to", "21625308299");
cntRqst.addArgument("from", "NEXMO");
cntRqst.addArgument("text", "reservation_annulée");
The advantage of this is the text is implicitly encoded and you can dynamically switch between GET/POST easily.
There is also the newer REST API (assuming result is JSON):
Response<Map> response = Rest.get("https://rest.nexmo.com/sms/json").
queryParam("api_key", API_KEY).
queryParam("api_secret", API_SECRET).
queryParam("to", "21625308299").
queryParam("from", "NEXMO").
queryParam("text", "reservation_annulée").
getAsJsonMap();
Related
I'm using socket.io for my chat app. I have an ArrayList which contains last message, username, time. Whenever a new message arrives in JSON format then it should check if JSON contained username is present in ArrayList or not. If present, then updates the ArrayList otherwise add in ArrayList.
Here is my code:-
private Emitter.Listener handle1 = new Emitter.Listener() {
#Override
public void call(final Object... args) {
ChatLists.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject)args[0];
try {
String sendername = data.getString("sender");
String lastMessage = data.getString("message");
String profileImage = data.getString("Profile");
String token = data.getString("fb_token");
chat_list chat_list = new chat_list(sendername,
profileImage, lastMessage, "0", "", "dummy", token);
if (chat_lists.size()==0){
chat_lists.add(chat_list);
}else {
for (int i=0;i<chat_lists.size();i++){
if (chat_lists.get(i).getContactname().equals(sendername)){
chat_lists.set(i,chat_list);
}else {
chat_lists.add(chat_list)
}
}
}
contactlistAdapter = new ContactlistAdapter(chat_lists);
recyclerView.setAdapter(contactlistAdapter);
contactlistAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
};
Well, you can use contains() & set() methods of ArrayList in a logical way to solve your problem like below:-
if(chat_lists.contains(username))
chat_lists.set(indexOf(username), new_username);
else chat_lists.add(new_username);
Try it:
if(chat_lists.contains(chat_list)){
chat_lists.remove(chat_list);
chat_lists.add(chat_list);
} else {
chat_lists.add(chat_list);
}
Read about architecture patterns, for example, MVP.
You need to store your messages somethere (in Model) and update view relative to data.
Also read about RecyclerView, cause of ListView is a little bit deprecated
if (chat_lists.get(i).getContactname().equals(sendername)){
above statement has problem them. It's not getting under your if condition and following the chat_lists.add(chat_list) statement.
Instead equals use ignoreCasequals. If still wont it solve your problem please use debug mode or logs check chat_lists.get(i).getContactname()
and sendername same or not.
I want to implement a very simple Java Telegram Client, which is capable of sending and receiving messages and store the sessions across multiple starts. I already managed to authenticate and receive messages
api = new TelegramApi(apiState, new AppInfo(API_ID, "console", "1", "1", "en"), new ApiCallback() {
#Override
public void onAuthCancelled(TelegramApi api) {
Log.d(TAG, "-----------------CANCELLED----------------");
Log.d(TAG, api.getApiContext().toString());
}
#Override
public void onUpdatesInvalidated(TelegramApi api) {
Log.d(TAG, "-----------------INVALIDATED----------------");
Log.d(TAG, api.getApiContext().toString());
}
#Override
public void onUpdate(TLAbsUpdates tlAbsUpdates) {
Log.d(TAG, "-----------------UPDATE----------------");
Log.d(TAG, tlAbsUpdates.toString());
if (tlAbsUpdates instanceof TLUpdateShortMessage) {
Log.d(TAG, "-----------------UPDATE CHAT MESSAGE----------------");
int senderId = ((TLUpdateShortMessage) tlAbsUpdates).getUserId();
Log.d(TAG, "Message from " + senderId);
String message = ((TLUpdateShortMessage) tlAbsUpdates).getMessage();
Log.d(TAG, message);
activity.appendMessage(TAG, message);
}
}
});
api.switchToDc(2);
TLConfig config = null;
try {
config = api.doRpcCallNonAuth(new TLRequestHelpGetConfig());
} catch (TimeoutException | IOException e) {
e.printStackTrace();
}
apiState.updateSettings(config);
However, I struggle to send messages to another user. For the beginning, it would be enough if I could send a message back to the user, who sent me a message before (by retrieving the senderId, as you can see in the onUpdate method before). However, if someone could also help me with retrieving the ids of my saved contacts, it would be perfect.
Furthermore, I want to store the sessions accross multiple startups, since I get a FLOOD_WAIT error (420), if I test my code to often.
For this I used https://github.com/rubenlagus/TelegramApi/blob/51713e9b6eb9e0ae0d4bbbe3d4deffff9b7f01e4/src/main/java/org/telegram/bot/kernel/engine/MemoryApiState.java and its used classes (e.g. TLPersistence), which stores and loads the ApiState. However, apparently it does not store the signin status, since I always have to authenticate my number every time I update the code.
By the way, I am using Api layer 66 (https://github.com/rubenlagus/TelegramApi/releases).
UPDATE 1:
Problems with sending messages solved myself:
private void sendMessageToUser(int userId, String message) {
TLInputPeerUser peer = new TLInputPeerUser();
peer.setUserId(userId);
TLRequestMessagesSendMessage messageRequest = new TLRequestMessagesSendMessage();
messageRequest.setFlags(0);
messageRequest.setPeer(peer);
messageRequest.setRandomId(new SecureRandom().nextLong());
messageRequest.setMessage(message);
api.doRpcCallNonAuth(messageRequest, 1500, new RpcCallback<TLAbsUpdates>() {
#Override
public void onResult(TLAbsUpdates tlAbsUpdates) {
Log.d(TAG, "-----------------------MESSAGE SENT-----------------------");
}
#Override
public void onError(int i, String s) {
Log.d(TAG, "-----------------------MESSAGE SENT ERROR-----------------------");
Log.d(TAG, String.valueOf(i));
if(s != null) {
Log.d(TAG, s);
}
}
});
}
However, now I am stuck at finding the userIds of my contacts.
After first update this is left:
Saving the session state (and signin state)
Find userIds of contacts
Update 2:
I managed to fetch the users, with which there are already dialogs. This is enough for my use case, however, loading all contacts would be perfect. This is how to load users from existing dialogs:
private int getUserId(String phone) throws InterruptedException {
TLRequestMessagesGetDialogs dialogs = new TLRequestMessagesGetDialogs();
dialogs.setOffsetId(0);
dialogs.setLimit(20);
dialogs.setOffsetPeer(new TLInputPeerUser());
CountDownLatch latch = new CountDownLatch(1);
api.doRpcCallNonAuth(dialogs, 1500, new RpcCallback<TLAbsDialogs>() {
#Override
public void onResult(TLAbsDialogs tlAbsDialogs) {
Log.d(TAG, "----------------------getUsers--------------------");
for(TLAbsUser absUser : ((TLDialogs) tlAbsDialogs).getUsers()) {
users.add((TLUser) absUser);
}
latch.countDown();
}
#Override
public void onError(int i, String s) {
Log.d(TAG, "----------------------getUsers ERROR--------------------");
latch.countDown();
}
});
latch.await();
for(TLUser user : users) {
if(user.getPhone().equals(phone)) {
return user.getId();
}
}
return 0;
}
After second update this is left:
Saving the session state (and signin state)
Get user ids from contacts instead of dialogs
I already read these topics:
how to use SignalR in Android
Android Client doesn't get data but .net client getting data from SignalR server
I write a simple chat system with Android that works with SignalR.
It is supposed to the clients send messages (by calling SendMessage method on the server) and the server should call the NewMessage method on the clients.
Here is my ChatHub class (simplified) written in C#.
public class ChatHub : Hub
{
// Store the clients connections Id
static readonly List<string> _connectedClients;
public override Task OnConnected()
{
// Keep connections id
// This section works fine and when the android device connects to the server,
// Its connection id will stored.
_connectedClients.Add(Context.ConnectionId)
//... other codes
}
public void SendMessage(string message)
{
foreach (var connectionId in _connectedClients)
{
// according to the logs
// android device connection id exists here
// and it works fine.
Clients.Client(connectionId).NewMessage(message);
}
}
}
When the android client connects to the server, On the OnConnected method, the connection id will be stored in the _connectedClients and it works fine.
In the SendMessage method of the ChatHub class, We have the android device connection id, and I'm sure that the android device is within the list
And here is my Andoird codes:
public class ChatActivity extends AppCompatActivity
{
// private fields
HubConnection connection;
HubProxy hub;
ClientTransport transport;
protected void onCreate(Bundle savedInstanceState) {
Logger logger = new Logger() {
#Override
public void log(String message, LogLevel logLevel) {
Log.e("SignalR", message);
}
};
Platform.loadPlatformComponent(new AndroidPlatformComponent());
connection = new HubConnection("192.168.1.100");
hub = connection.createHubProxy("chatHub"); // case insensitivity
transport = new LongPollingTransport(connection.getLogger());
// no difference when using this:
//transport = new ServerSentEventsTransport(connection.getLogger());
// this event never fired!
hub.subscribe(new Object() {
public void NewMessage(String message)
{
Log.d("<Debug", "new message received in subscribe"); // won't work!
}
}
// this event never fired!
hub.on("NewMessage", new SubscriptionHandler() {
#Override
public void run() {
Log.d("<Debug", "new message received in `on`"); // won't work!
}
});
// connect to the server that works fine.
SignalRFuture<Void> awaitConnection = connection.start(transport);
try {
awaitConnection.get(); // seems useless when using this or not!
}
catch (Exception ex) {
}
// this method works fine.
hub.invoke("sendMessage", "this is a test message to the server")
.done(new Action<Void>() {
#Override
public void run(Void aVoid) throws Exception {
Log.d("<Debug", "message sent."); // Works fine
}
});
}
}
In the above java code, invoking the sendMessage on the server works fine and the server get the messages.
But the only problem is that the hub.on(...) or hub.subscribe(...) events are never be called by the server.
In a simple description, My app can send message, but can not receive message from the others.
Any suggestion will be appreciated.
For the futures this is the way I finally achieved the answer (please first read the question android codes):
public class ChatActivity extends AppCompatActivity
{
// private fields
HubConnection connection;
HubProxy hub;
ClientTransport transport;
protected void onCreate(Bundle savedInstanceState) {
Logger logger = new Logger() {
#Override
public void log(String message, LogLevel logLevel) {
Log.e("SignalR", message);
}
};
Platform.loadPlatformComponent(new AndroidPlatformComponent());
connection = new HubConnection("192.168.1.100");
hub = connection.createHubProxy("chatHub"); // case insensitivity
/* ****new codes here**** */
hub.subscribe(this);
transport = new LongPollingTransport(connection.getLogger());
/* ****new codes here**** */
connection.start(transport);
/* ****new codes here**** */
/* ****seems useless but should be here!**** */
hub.subscribe(new Object() {
#SuppressWarnings("unused")
public void newMessage(final String message, final String messageId, final String chatId,
final String senderUserId, final String fileUrl, final String replyToMessageId) {
}
});
/* ********************** */
/* ****new codes here**** */
/* **** the main method that I fetch data from server**** */
connection.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(final JsonElement json) {
runOnUiThread(new Runnable() {
public void run() {
JsonObject jsonObject = json.getAsJsonObject();
Log.e("<Debug>", "response = " + jsonObject.toString());
}
});
}
});
/* ********************** */
}
}
!important note:
The priority of the codes is important. this is how I fix my problem in this topic.
You does not provider parameters in your client-side which should be same as your side-site. The code should be below:
hub.on("NewMessage", new SubscriptionHandler1<String>() {
#Override
public void run(String message) {
Log.d("<Debug", "new message received in `on`");
}
},String.class); //do not forget say the String class in the end
i used the java telegram api to communicate with telegram core api in windows intellij idea
https://github.com/ex3ndr/telegram-api
But the app is facing Timeout error in line TLConfig config = api.doRpcCall(new TLRequestHelpGetConfig());Full source code:
AppInfo appinfo=new AppInfo(45687, "Myapp", "154", "587","en");
TLRequestAuthCheckPhone checkRequest = new TLRequestAuthCheckPhone("96521452365");
MyApiStorage state=new MyApiStorage();
TelegramApi api = new TelegramApi(state, appinfo, new ApiCallback()
{
public void onApiDies(TelegramApi api) {
// When auth key or user authorization dies
}
#Override
public void onUpdatesInvalidated(TelegramApi api) {
System.out.print("############################### onUpdatesInvalidated");
// When api engine expects that update sequence might be broken
}
#Override
public void onAuthCancelled(TelegramApi ta) {
System.out.print("############################### onAuthCancelled");
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void onUpdate(TLAbsUpdates updates) {
System.out.print("############################### onUpdate");
System.out.println("user Id ::::"+((TLUpdateShortMessage) updates).getFromId());
}
});
api.switchToDc(1);
TLConfig config = api.doRpcCall(new TLRequestHelpGetConfig());
System.out.print("############################### config" + config.getTestMode());
state.updateSettings(config);
api.doRpcCall(checkRequest, new RpcCallbackEx<TLCheckedPhone>() {
public void onConfirmed() {
System.out.print("############################### onConfirmed");
}
public void onResult(TLCheckedPhone result) {
boolean invited = result.getPhoneInvited();
boolean registered = result.getPhoneRegistered();
System.out.print("############################### onResult" + registered);
// TODO process response further
}
public void onError(int errorCode, String message) {
System.out.print("############################### onError" + message);
}
});
can someone help me
Your timeout might happen for several reasons:
1. You are using
api.doRpcCall(new TLRequestHelpGetConfig());
In the TelegramApi class this translates into
return this.doRpcCall(method, timeout, 0);
0 there stands for DC. If your DC is different you will timeout
2. There were suggestions in other places to use doRpcCallSide instead and it worked for some and not for others. The reason is it translates into
return this.doRpcCall(method, 15000, this.primaryDc, true);
where true stands authRequired.
3. If you want to do this without authorization then use api.doRpcCallNonAuth
I am working on a Facebook application and am currently trying to have my app tag one of the user's friends. I almost have it working 100%, except when it is supposed to be tagging the person, I instead get an error message that follows:
{"error":{"message":"Unsupported post request.","type":"GraphMethodException","code":100}}
The user and photo IDs are for sure correct, that is not the issue. Otherwise, I'm not sure what else could be causing this error. Code is below for reference. Thanks much!
public void setTag() {
String relativePath = Constants.photoID + "/tags/" + Constants.userID;
Bundle params = new Bundle();
params.putString("x", "5");
params.putString("y", "5");
Constants.mAsyncRunner.request(relativePath, params, "POST", new TagPhotoRequestListener(),
null);
}
public class TagPhotoRequestListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
if (response.equals("true"))
{
String message = "User tagged in photo at (5, 5)" + "\n";
message += "Api Response: " + response;
Log.i("TagPhotoRequestListener", message);
}
else
{
Log.w("TagPhotoRequestListener", "User could not be tagged.");
}
}
public void onFacebookError(FacebookError e) {
Log.w("TagPhotoRequestListener", "Facebook Error: " + e.getMessage());
}
}
EDIT: Here is my code for posting of a picture and getting the photoID. For testing purposes it's just a single photo from my sdcard.
public void postPhoto() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/mnt/sdcard/Download/KathleenSchedule.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, Constants.mFacebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(Constants.mFacebook);
mAsyncRunner.request(null, params, "POST", new PhotoUploadListener(), null);
}
public class PhotoUploadListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("PhotoUploadListener", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
System.out.println(response);
final String photo_id = json.getString("pid");
Constants.photoID = photo_id;
Ok, now your problem is clear.
You are using the photos.upload method which is deprecated:
We are in the process of deprecating the REST API, so if you are
building a new application you shouldn't use this function. Instead
use the Graph API and POST to the photos connection of the User object
Because you are using an old method, you're getting and old response type.
Switch to using the graph api way, and you should get the photo id in the response.