I'm new to Twitters API and Twitter's twitter4j library. I've recently registered an app to be able to use Twitter's API. Twitter has granted me consumer API keys (API key & API secret key), as well as an access token & access token secret.
The problem is, I've been trying to use twitter4j to authenticate into twitter (using the aforementioned keys), but when trying to access any of the APIs resources, I get an error saying I'm not allowed access due to a rate limit. But how can I possibly have reached a rate limit when I've never been able to query the api? :,(
This is what I'm attempting (with sensitive bits replaced by dummy values):
#SpringBootApplication
public class App
{
private static final String CONSUMER_KEY = "FakeConsumerKey";
private static final String CONSUMER_SECRET = "FakeConsumerSecret";
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
System.out.println("Making an authentication request to"
+ " retrieve the bearer token...");
OAuth2Token token;
token = getOAuth2Token();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(true);
cb.setOAuthConsumerKey(CONSUMER_KEY);
cb.setOAuthConsumerSecret(CONSUMER_SECRET);
cb.setOAuth2TokenType(token.getTokenType());
cb.setOAuth2AccessToken(token.getAccessToken());
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
try {
System.out.println("My screen name: " + twitter.getScreenName());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static OAuth2Token getOAuth2Token()
{
OAuth2Token token = null;
ConfigurationBuilder cb;
cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(true);
cb.setOAuthConsumerKey(CONSUMER_KEY);
cb.setOAuthConsumerSecret(CONSUMER_SECRET);
try
{
token = new TwitterFactory(cb.build())
.getInstance().getOAuth2Token();
System.out.println("token: " + token.getAccessToken());
}
catch (Exception e)
{
System.out.println("Can't get OAuth2 token");
e.printStackTrace();
System.exit(0);
}
return token;
}
}
This is the error returned:
403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
message - Your credentials do not allow access to this resource
code - 220
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=9a9caf7a or
http://www.google.co.jp/search?q=bf94ba05
TwitterException{exceptionCode=[9a9caf7a-bf94ba05], statusCode=403, message=Your credentials do not allow access to this resource, code=220, retryAfter=-1, rateLimitStatus=null, version=4.0.6}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
at twitter4j.TwitterBaseImpl.fillInIDAndScreenName(TwitterBaseImpl.java:133)
at twitter4j.TwitterBaseImpl.fillInIDAndScreenName(TwitterBaseImpl.java:128)
at twitter4j.TwitterBaseImpl.getScreenName(TwitterBaseImpl.java:108)
at com.vismark.social.twitter.TwitterAccountService.App.main(App.java:41)
Where did I go wrong?
Definition of getScreenName
"Returns authenticating user's screen name.
This method may internally call verifyCredentials() on the first invocation if
- this instance is authenticated by Basic and email address is supplied instead of screen name, or - this instance is authenticated by OAuth."
User-based authentication has to use OAuth 1.0a not OAuth 2. You need to get access tokens, follow this :
https://developer.twitter.com/en/docs/basics/authentication/overview/using-oauth
When you get your access tokens, just update your ConfigurationBuilder like this :
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(false);
cb.setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRET)
.setOAuthAccessToken(ACCESS_TOKEN)
.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
It is clearly mentioned that the number of Requests allotted via application-only auth for search/tweets is 450/15 minutes. I am using twitter4j version 4.0.1 but, I am getting only 180 requests/15 minutes via application-only auth.
I tried to get the limit using the code below and I got the limit as 450. But, am getting the rate limit exceeded error after 180 requests.
twitter.getRateLimitStatus().get("/search/tweets").getLimit();
Where did I go wrong?
Update
public static OAuth2Token getOAuth2Token(String key, String sec) {
OAuth2Token token = null;
ConfigurationBuilder cb;
cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(true);
cb.setOAuthConsumerKey(key).setOAuthConsumerSecret(sec);
try
{
token = new TwitterFactory(cb.build()).getInstance().getOAuth2Token();
}
catch (Exception e)
{
System.out.println("Could not get OAuth2 token");
e.printStackTrace();
System.exit(0);
}
return token;
}
public TwitterManager() throws TwitterException {
OAuth2Token token;
token = getOAuth2Token("XXXX","XXXX");
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setApplicationOnlyAuthEnabled(true);
cb.setOAuthConsumerKey("XXXX");
cb.setOAuthConsumerSecret("XXXX");
cb.setOAuth2TokenType(token.getTokenType());
cb.setOAuth2AccessToken(token.getAccessToken());
twitter = new TwitterFactory(cb.build()).getInstance();
}
This is how I used application-only auth.
Are you able to share any more of your code?
From the results, I suspect you are not using application-only, but maybe have used another oauth flow?
it says Stream Closed error
public class StreamAPI {
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("xxxx");
cb.setOAuthConsumerSecret("xxx");
cb.setOAuthAccessToken("xx-xx");
cb.setOAuthAccessTokenSecret("xxx");
cb.setUseSSL(true);
cb.setUserStreamRepliesAllEnabled(true);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
AccessToken accestoken = new AccessToken("xx-xx", "xxx");
twitterStream.setOAuthAccessToken(accestoken);
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
#Override
public void onStallWarning(StallWarning stallWarning) {
//To change body of implemented methods use File | Settings | File Templates.
}
public void onException(Exception ex) {
ex.printStackTrace();
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"France", "Germany"};
fq.track(keywords);
twitterStream.addListener(listener);
twitterStream.filter(fq);
}
}
i am getting error
Stream closed.
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=a8fd061d or
http://www.google.co.jp/search?q=00070a0c
TwitterException{exceptionCode=[a8fd061d-00070a0c a8fd061d-0007099d], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
at twitter4j.StatusStreamBase.handleNextElement(StatusStreamBase.java:199)
at twitter4j.StatusStreamImpl.next(StatusStreamImpl.java:57)
at twitter4j.TwitterStreamImpl$TwitterStreamConsumer.run(TwitterStreamImpl.java:478)
Caused by: java.io.IOException: the end of the stream has been reached
at twitter4j.StatusStreamBase.handleNextElement(StatusStreamBase.java:88)
... 2 more
But the same configuration works for TwitterAPI
Twitter gives the following reasons why you may be disconnected:
A client establishes too many connections with the same credentials. When this occurs, the oldest connection will be terminated. This means
you have to be careful not to run two reconnecting clients in parallel
with the same credentials, or else they will take turns disconnecting
each other.
A client stops reading data suddenly. If the rate of Tweets being read off of the stream drops suddenly, the connection will be closed.
A client reads data too slowly. Every streaming connection is backed
by a queue of messages to be sent to the client. If this queue grows
too large over time, the connection will be closed.
A streaming server is restarted. This is usually related to a code deploy and is not very frequent.
Twitter's network configuration changes. These events are extremely rare, and would represent load balancer restarts or network
reconfigurations, for example.
You should receive information on why you were disconnected, but not always:
Streams may be shut down for a variety of reasons. The streaming API will attempt to deliver a message indicating why a stream was closed. Note that if the disconnect was due to network issues or a client reading too slowly, it is possible that this message will not be received.
My thought would be that perhaps you're not reading data quickly enough - although I can't say for certain. Try implementing onStallWarning to see if you're getting any stall warnings, e.g.:
#Override
public void onStallWarning(StallWarning stallWarning) {
System.out.println(stallWarning);
}
In my project I am trying to integrate twitter using twitter4j.I tried sample code to login in office and I could post tweet successfully using that,but coming back to home I am facing bizarre problem in JCE.Jar which says
Failed to get HmacSHA1 "Message Authentication Code" (MAC)
java.security.NoSuchAlgorithmException: Algorithm HmacSHA1 not available
at javax.crypto.Mac.getInstance(DashoA13*..)
at twitter4j.auth.OAuthAuthorization.generateSignature(OAuthAuthorization.java:317)
at twitter4j.auth.OAuthAuthorization.generateAuthorizationHeader(OAuthAuthorization.java:227)
at twitter4j.auth.OAuthAuthorization.generateAuthorizationHeader(OAuthAuthorization.java:273)
at twitter4j.auth.OAuthAuthorization.getAuthorizationHeader(OAuthAuthorization.java:75)
at twitter4j.internal.http.HttpClientImpl.setHeaders(HttpClientImpl.java:237)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:113)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:269)
at org.twitterstats.App.main(App.java:23)
Exception in thread "main" java.lang.AssertionError: java.security.NoSuchAlgorithmException: Algorithm HmacSHA1 not available
at twitter4j.auth.OAuthAuthorization.generateSignature(OAuthAuthorization.java:337)
at twitter4j.auth.OAuthAuthorization.generateAuthorizationHeader(OAuthAuthorization.java:227)
at twitter4j.auth.OAuthAuthorization.generateAuthorizationHeader(OAuthAuthorization.java:273)
at twitter4j.auth.OAuthAuthorization.getAuthorizationHeader(OAuthAuthorization.java:75)
at twitter4j.internal.http.HttpClientImpl.setHeaders(HttpClientImpl.java:237)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:113)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:269)
at org.twitterstats.App.main(App.java:23)
Caused by: java.security.NoSuchAlgorithmException: Algorithm HmacSHA1 not available
at javax.crypto.Mac.getInstance(DashoA13*..)
at twitter4j.auth.OAuthAuthorization.generateSignature(OAuthAuthorization.java:317)
... 12 more
<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>[2.2,)</version>
</dependency>
Code to login into twitter is somewhat like like this.
public static void main(String args[]) thrwos Exception{
// The factory instance is re-useable and thread safe.
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken) {
System.out.println("Open the following URL and grant access to your account:");
System.out.println(requestToken.getAuthorizationURL());
System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
String pin = br.readLine();
try{
if(pin.length() > 0){
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
}else{
accessToken = twitter.getOAuthAccessToken();
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()){
System.out.println("Unable to get the access token.");
}else{
te.printStackTrace();
}
}
}
//persist to the accessToken for future reference.
storeAccessToken(twitter.verifyCredentials().getId() , accessToken);
Status status = twitter.updateStatus(args[0]);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
System.exit(0);
}
private static void storeAccessToken(int useId, AccessToken accessToken){
//store accessToken.getToken()
//store accessToken.getTokenSecret()
}
Though I am not very sure why this problem occurred but just attempted version upgrading to Java 7 and it worked!
What are the possible ways to send and receive sms from Java application?
How?
(Disclaimer: I work at Twilio)
Twilio offers a Java SDK for sending SMS via the Twilio REST API.
if all you want is simple notifications, many carriers support SMS via email; see SMS through E-Mail
There is an API called SMSLib, it's really awesome.
http://smslib.org/
Now you have a lot of Saas providers that can give you this service using their APIs
Ex: mailchimp, esendex, Twilio, ...
The best SMS API I've seen in Java is JSMPP. It is powerful, easy to use, and I used it myself for an enterprise-level application (sending over 20K SMS messages daily).
This API created to reduce the verbosity of the existing SMPP API.
It's very simple and easy to use because it hides the complexity of
the low level protocol communication such as automatically enquire
link request-response.
https://code.google.com/p/jsmpp/
I've tried some other APIs such as Ozeki, but most of them either is commercial or has limitation in its throughput (i.e can't send more than 3 SMS messages in a second, for example).
You Can Do this With A GSM Modem and Java Communications Api [Tried And Tested]
First You Need TO Set Java Comm Api
This Article Describes In Detail How to Set Up Communication Api
Next You Need A GSM Modem (preferably sim900 Module )
Java JDK latest version preferable
AT Command Guide
Code
package sample;
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.io.*;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;
public class GSMConnect implements SerialPortEventListener,
CommPortOwnershipListener {
private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
private String messageString = "";
private CommPortIdentifier portId = null;
private Enumeration portList;
private InputStream inputStream = null;
private OutputStream outputStream = null;
private SerialPort serialPort;
String readBufferTrial = "";
/** Creates a new instance of GSMConnect */
public GSMConnect(String comm) {
this.comPort = comm;
}
public boolean init() {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(comPort)) {
System.out.println("Got PortName");
return true;
}
}
}
return false;
}
public void checkStatus() {
send("AT+CREG?\r\n");
}
public void send(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String phoneNumber, String message) {
char quotes ='"';
send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
send(message + '\032');
System.out.println("Message Sent");
}
public void hangup() {
send("ATH\r\n");
}
public void connect() throws NullPointerException {
if (portId != null) {
try {
portId.addPortOwnershipListener(this);
serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (PortInUseException | UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
/** These are the events we want to know about*/
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnRingIndicator(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
//Register to home network of sim card
send("ATZ\r\n");
} else {
throw new NullPointerException("COM Port not found!!");
}
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[2048];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(numBytes);
if((readBuffer.toString()).contains("RING")){
System.out.println("Enter Inside if RING Loop");
}
}
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public void outCommand(){
System.out.print(readBufferTrial);
}
public void ownershipChange(int type) {
switch (type) {
case CommPortOwnershipListener.PORT_UNOWNED:
System.out.println(portId.getName() + ": PORT_UNOWNED");
break;
case CommPortOwnershipListener.PORT_OWNED:
System.out.println(portId.getName() + ": PORT_OWNED");
break;
case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
System.out.println(portId.getName() + ": PORT_INUSED");
break;
}
}
public void closePort(){
serialPort.close();
}
public static void main(String args[]) {
GSMConnect gsm = new GSMConnect(comPort);
if (gsm.init()) {
try {
System.out.println("Initialization Success");
gsm.connect();
Thread.sleep(5000);
gsm.checkStatus();
Thread.sleep(5000);
gsm.sendMessage("+91XXXXXXXX", "Trial Success");
Thread.sleep(1000);
gsm.hangup();
Thread.sleep(1000);
gsm.closePort();
gsm.outCommand();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Can't init this card");
}
}
}
You can use Nexmo to send SMS as well as receive SMS.
Sending SMS with the Nexmo Java Library is fairly straightforward. After creating a new account, renting a virtual number, and getting your API key & secret you can use the library to send SMS like so:
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(API_KEY, API_SECRET);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo!");
//There may be more than one response if the SMS sent is more than 160 characters.
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
To receive SMS you'll need to set up a server that consumes a webhook. That's fairly simple as well. I recommend checking out our tutorial on receiving SMS with Java.
Disclosure: I work for Nexmo
There are two ways :
First : Use a SMS API Gateway which you need to pay for it , maybe you find some trial even free ones but it's scarce .
Second : To use AT command with a modem GSM connected to your laptop .
that's all
TextMarks gives you access to its shared shortcode to send and receive text messages from your app via their API. Messages come from/to 41411 (instead of e.g. a random phone# and unlike e-mail gateways you have the full 160 chars to work with).
You can also tell people to text in your keyword(s) to 41411 to invoke various functionality in your app. There is a JAVA API client along with several other popular languages and very comprehensive documentation and technical support.
The 14 day free trial can be easily extended for developers who are still testing it out and building their apps.
Check it out here: TextMarks API Info
OMK.smpp. API. it's base on SMPP
and simulator is also available for free
LOGICA SMPP API.
And another option is Kannel a free WAP and SMS gateway.
I suggest a cloud based solution like Twilio. Cloud based solutions are cost-effective, than an in-house solution as the there is no ongoing maintenance, required. SMS through email is not an elegant solution, as you have to get the carrier information from the user and you can never be sure that you can text all mobile numbers.
I am using twilio java api in my web application, to send sms from serverside. within few minutes, you can integrate with your app.
https://www.twilio.com/docs/java/install
Here's an example sending an SMS message from the docs:
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;
import com.twilio.sdk.resource.instance.Message;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
public class Example {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "{{ account_sid }}";
public static final String AUTH_TOKEN = "{{ auth_token }}";
public static void main(String[] args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build a filter for the MessageList
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Body", "Test Twilio message"));
params.add(new BasicNameValuePair("To", "+14159352345"));
params.add(new BasicNameValuePair("From", "+14158141829"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
You can you LOGICA SMPP Java API for sending and Recieving SMS in Java application.
LOGICA SMPP is well proven api in telecom application. Logica API also provide you with signalling capicity on TCP/IP connection.
You can directly integrate with various telecom operator accross the world.
It depends on how you're going to work and who your provider is.
If you work with a sms-gateway company you'll probably work through SMPP protocol (3.4 is still the most common), then have a look on OpenSMPP and jSMPP. These are powerful libs to work with SMPP.
If you're going to work with your own hardware (f.e. a gsm-modem) the easiest way to send messages is through AT commands, they differ depends on the model, so, you should find out what AT commands is supported by your modem. Next, if your modem has an IP and open to connection, you can send commands through java socket
Socket smppSocket = new Socket("YOUR_MODEM_IP", YOUR_MODEM_PORT);
DataOutputStream os = new DataOutputStream(smppSocket.getOutputStream());
DataInputStream is = new DataInputStream(smppSocket.getInputStream());
os.write(some_byte_array[]);
is.readLine();
Otherwise you'll work through a COM port, but the method is the same (sending AT commands), you can find more information how to work with serial ports here.
You can use Twilio for this. But if you are looking for some tricky workaround you can follow the workaround I have mentioned below.
This is not possible for receiving sms. But this is a tricky method you can use to send sms to number of clients. You can use twitter API. We can follow twitter account from our mobile phone with a sms. We just have to send sms to twitter. Imagine we create a twitter account with the user name of #username. Then we can send sms to 40404 as shown below.
follow #username
Then we start to get tweets which are tweeted in that account.
So after we create a twitter account then we can use Twitter API to post tweets from that account. Then all the clients who have follow that account as I mentioned before start to receiving tweets.
You can learn how to post tweets with twitter API from following link.
Twitter API
Before you start developing you have to get permission to use twitter api. You can get access to twitter api from following link.
Twitter Developer Console
This is not the best solution for your problem.But hope this help.
We also love Java in Wavecell, but this question can be answered without language-specific details since we have a REST API which will cover most of your needs:
curl -X "POST" https://api.wavecell.com/sms/v1/amazing_hq/single \
-u amazing:1234512345 \
-H "Content-Type: application/json" \
-d $'{ "source": "AmazingDev", "destination": "+6512345678", "text": "Hello, World!" }'
Look at this questions if you have problems with sending HTTP requests in Java:
HTTP POST using JSON in Java
How can I send json object in http post in java
For specific cases you can also consider using the SMPP API and already mentioned JSMPP library will help with that.
There is Ogham library. The code to send SMS is easy to write (it automatically handles character encoding and message splitting). The real SMS is sent either using SMPP protocol (standard SMS protocol) or through a provider.
You can even test your code locally with a SMPP server to check the result of your SMS before paying for real SMS sending.
package fr.sii.ogham.sample.standard.sms;
import java.util.Properties;
import fr.sii.ogham.core.builder.MessagingBuilder;
import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.sms.message.Sms;
public class BasicSample {
public static void main(String[] args) throws MessagingException {
// [PREPARATION] Just do it once at startup of your application
// configure properties (could be stored in a properties file or defined
// in System properties)
Properties properties = new Properties();
properties.setProperty("ogham.sms.smpp.host", "<your server host>"); // <1>
properties.setProperty("ogham.sms.smpp.port", "<your server port>"); // <2>
properties.setProperty("ogham.sms.smpp.system-id", "<your server system ID>"); // <3>
properties.setProperty("ogham.sms.smpp.password", "<your server password>"); // <4>
properties.setProperty("ogham.sms.from.default-value", "<phone number to display for the sender>"); // <5>
// Instantiate the messaging service using default behavior and
// provided properties
MessagingService service = MessagingBuilder.standard() // <6>
.environment()
.properties(properties) // <7>
.and()
.build(); // <8>
// [/PREPARATION]
// [SEND A SMS]
// send the sms using fluent API
service.send(new Sms() // <9>
.message().string("sms content")
.to("+33752962193"));
// [/SEND A SMS]
}
}
There are many other features and samples / spring samples.
You can use AT & T commands for sending sms using GSM modem.