Sending SMS through low end API - java

I have a message constructor method of the form:
public static String constructMsg(CustomerInfo customer) {
... snipped
String msg = String.format("Snipped code encapsulated by customer object");
return msg;
}
The API link is:
http://xxx.xxx.xx.xx:8080/bulksms?username=xxxxxxx &password=xxxx &type=0 &dlr=1&destination=10digitno & source=xxxxxx& message=xxxxx
In my main method I have(s):
List<CustomerInfo> customer = dao.getSmsDetails(userDate);
theLogger.info("Total No : " + customer.size() );
if (!customer.isEmpty()) {
for (CustomerInfo cust : customer) {
String message = constructMsg(cust);
// Add link and '?' and query string
// use URLConnection's connect method
}
}
So I am using connect method of URLConnection. The API does not have any documentation. Is there any way for checking response?
My other question is, I have been advised to use ThreadPoolExecutor. How would I use use it here?

This method use HTTPURLConnection to perform a GET request returning the response as a String. There're many way to do it, this is not particularly brilliant but it's really readable.
public String getResponse(String url, int timeout) {
HttpURLConnection c;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
default:
return "HTTP CODE: "+status;
}
} catch (MalformedURLException ex) {
Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
} finally{
if(c!=null) c.disconnect();
}
return null;
}
Call this method like this:
getResponse("http://xxx.xxx.xx.xx:8080/bulksms?username=xxxxxxx&password=xxxx&type=0 &dlr=1&destination=10digitno&source=xxxxxx&message=xxxxx",2000);
I assume the whitespaces in your URL are not supposed to be there.

Related

Force java.net.HttpUrlConnection to return GET-response regardless of Http-Status-Code

I'm working on a HTTP-Client to sent GET-Requests to an API, which responds with proper JSON-Objects even when the HTTP-Status Codes contains an Error such as 401.
public String get(String url){
URL target;
HttpURLConnection connection;
int code = 200;
BufferedReader reader;
String inputLine;
String result = null;
try {
target = new URL(url);
} catch (MalformedURLException ex) {
return result;
}
try {
connection = (HttpURLConnection)target.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//code = connection.getResponseCode();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
result = "";
while ((inputLine = reader.readLine()) != null){
result += inputLine;
}
reader.close();
} catch (IOException ex) {
return "...";
}
return result;
}
When that's the case, the IOException is thrown and the response isn't written. However, I want to receive the response regardless of the HTTP-Status-Code and hande error handling myself. How can I achieve this?
I don't believe you can do that, but there's https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream-- for getting the payload in case of an error.

Android - If statement gets ignored and bypassed

I am calling a PHP script from a function like this:
public static String XSSignUp(String username, String password, String email, String signInWith) {
// Paramenters
Map<String, Object> params = new LinkedHashMap<>();
params.put(USERS_USERNAME, username);
params.put(USERS_PASSWORD, password);
params.put(USERS_EMAIL, email);
params.put("signInWith", signInWith);
params.put(USERS_IOS_DEVICE_TOKEN, IOS_DEVICE_TOKEN);
params.put(USERS_ANDROID_DEVICE_TOKEN, ANDROID_DEVICE_TOKEN);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
try { postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
postData.append('=');
try { postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
}
byte[] postDataBytes;
postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url;
url = new URL(TABLES_PATH + "m-signup.php?");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
// Get response
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) { stringBuilder.append(line).append("\n"); }
responseStreamReader.close();
String response = stringBuilder.toString();
responseStream.close();
conn.disconnect();
Log.i(TAG, "XSSignUp -> RESPONSE: " + response + "\n-----------------\n");
if (response.equals("e_101")) { return E_101;
} else if (response.equals("e_102")) { return E_102;
} else { return response; }
// error
} else { return "Something went wrong. Try again."; }
} catch (IOException e) { e.printStackTrace(); return e.getMessage(); }
}
This is how I call that function:
final String sup = XSSignUp(usernameTxt.getText().toString(), passwordTxt.getText().toString(), emailTxt.getText().toString(), "");
Log.i(TAG, "SUP: " + sup);
// errors
if (sup.matches("e_101")) {
hideHUD();
simpleAlert(E_101, ctx);
} else if (sup.matches("e_102")) {
hideHUD();
simpleAlert(E_102, ctx);
} else {
Log.i(TAG, "YES, SIGN UP!");
}
So, if I run my app and fill a signup form using johndoe as username, my PHP script returns a response string as "e_101" (username already exists), and it prevents the script to add records to my database. I get this message in the Logcat:
I/log-: XSSignUp -> RESPONSE: e_101
I/log-: SUP: e_101
I/log-: YES, SIGN UP!
Which is wrong, because I shouldn't get the last line: I/log-: YES, SIGN UP!.
This compromises my app because instead of firing an alert dialog (simpleAlert(E_101, ctx);), it goes on and skips that part.
I don't really understand why the IF statement doesn't work, because I've also tried to do this:
final String sup = XSSignUp(usernameTxt.getText().toString(), passwordTxt.getText().toString(), emailTxt.getText().toString(), "");
sup = "e_101"; <-- FORCING THE sup STRING TO BE "e_101"!
// errors
if (sup.matches("e_101")) {
hideHUD();
simpleAlert(E_101, ctx);
} else if (sup.matches("e_102")) {
hideHUD();
simpleAlert(E_102, ctx);
} else {
Log.i(TAG, "YES, SIGN UP!");
}
and then it works! But it doesn't make any sense to me since the sup string is the same as the one that my function returns from the PHP script, as you can see by the Logcat messages...
I've also tried using equals():
sup.equals("e_101")
No positive result, so what am I doing wrong?
Your response contains extra new line \n, that's why if not work.
The problem is in here:
stringBuilder.append(line).append("\n");
Try to change it like below:
int i = 0;
while ((line = responseStreamReader.readLine()) != null) {
if(i != 0)
stringBuilder.append("\n");
stringBuilder.append(line);
i++;
}
Or
....
stringBuilder.replace(stringBuilder.lastIndexOf("\n"), stringBuilder.length(),"");
String response = stringBuilder.toString();
Beside this as you change the CASE of your response to upper inside XSSignUp and compare with lower CASE outside, you have to use equalsIgnoreCase instead of equals like
sup.equalsIgnoreCase("e_101")

HttpUrlConnection BadRequest - Statuscode 400

I have implemented a class using HttpUrlConnection to get some data from the google geocoding api. When I'm using this code on android, it works properly. But as soon as I am using this code in another "normal" java program, I am getting the status-code 400 (BadRequest) sometimes. Here is my code:
HttpURLConnection c = null;
StringBuilder sb = new StringBuilder();
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_CREATED:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
}
} catch (SocketTimeoutException ex){
// Handle ...
} catch (MalformedURLException ex) {
// Handle ...
} catch (IOException ex) {
// Handle ...
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
}
}
}
I have a reliable internet connection and also the URL I am using to receive the data works, whenever I try it with my web browser.
Thanks in advance!
Bad Request is often caused by inadequat URLs. As you mentioned not every URL gives this error, only a view of them. So it has to be something to do with that. Try the following code to ensure the correct encoding of the URL you are using:
String url = ...; // your url
url = URLEncoder.encode(url,"UTF-8");
// Use 'url' ...

AsyncTask LIFX Bulb response

I have got problem with read output form request.
public JSONArray listLights()
{
try
{
URL adres = new URL("https://api.lifx.com/v1/lights/all");
HttpURLConnection polaczenie = (HttpURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
BufferedReader wejscie = new BufferedReader(new InputStreamReader((polaczenie.getInputStream())));
StringBuilder odpowiedz = new StringBuilder();
String json;
while ((json = wejscie.readLine()) != null)
odpowiedz.append(json);
wejscie.close();
return new JSONArray(odpowiedz.toString());
}
catch (Exception wyjatek)
{
wyjatek.printStackTrace();
}
return new JSONArray();
}
StackTrace
I added to AndroidManifest Internet access too.
Welcome to leave any comments. :P
EDIT:
I google internet and found partial solution. Added AsyncTask, but now I'm receiving '429' response code.
public class JSONTask extends AsyncTask<String, String, String>
{
String apiKey = "blah_blah_blah";
String txtresult;
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try
{
URL adres = new URL(params[0]);
HttpsURLConnection polaczenie = (HttpsURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
System.out.println(polaczenie.getResponseCode());
InputStream stream = polaczenie.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null)
{
buffer.append(line);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
if (connection != null)
connection.disconnect();
try
{
if (reader != null)
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
widok.setText(s);
}
}
My current StackTrace
EDIT2:
New day, new surprise. I figure out that I'm making connection with Bulb once/twice on every 10 attempts. Any ideas?
HTTP Status code 429 means too many requests in a given an amount of time. So how many requests exactly are you doing?
android.os.NetworkOnMainThreadException it means, that You have to make a htttp request from another threat than UIthread. Why are you using async task ?
Edit: You can also try make a call from postman and maybe You will see the problem.
In the end, everything is working. Problem was on the side of bulb or Lifx Cloud.

Retrieving JSON from a Web API on Android

Here... I have a Web API with a MessageController that will respond to my request from Android and send JSON (Hello World - Just to test it out).
public class MessageController : ApiController
{
public async Task<IHttpActionResult> SendAsync()
{
return Ok(new { text = "hello world" });
}
}
From my Android App I want to request JSON from my API. I have requested from other Web APIs like currency etc. And it worked, but same method don't work on my API.
Here it is:
public void requestMessagesFromApi(View v)
throws ClientProtocolException, IOException {
final String response = getJSON(finalUrl);
TextView msgTV = (TextView) findViewById(R.id.msgTxt);
msgTV.setText(response);
}
public String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
I get ResonseCode -1. Don't know why. In Final URL I am targeting my Web API on Azure:
finalUrl ="http://<hereIsMineWebApiURL>/api/message"
I'm sure that I'm wrong in API.

Categories