I need to send an SMS through my Java Application. I had piece of code that used to work perfectly well where I had made use of a SMS sending site. However the site introduced captcha verification because of which my code fails. Please find the below code that I had tried. Request you to please guide me through any other alternatives that I can make use of sending SMS through Java.
package com.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class Mobiletry2
{
private final String LOGIN_URL = "http://*****.com/login.php";
private final String SEND_SMS_URL = "http://*****.com/home.php";
private final String LOGOUT_URL = "http://*****.com/logout.php?LogOut=1";
private final int MESSAGE_LENGTH = 10;
private final int MOBILE_NUMBER_LENGTH = 140;
private final int PASSWORD_LENGTH = 10;
private String mobileNo;
private String password;
private DefaultHttpClient httpclient;
Mobiletry2(String username,String password)
{
this.mobileNo = username;
this.password = password;
httpclient = new DefaultHttpClient();
}
public boolean isLoggedIn() throws IOException {
// User Credentials on Login page are sent using POST
// So create httpost object
HttpPost httpost = new HttpPost(LOGIN_URL);
// Add post variables to login url
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("MobileNoLogin", mobileNo));
nvps.add(new BasicNameValuePair("LoginPassword", password));
httpost.setEntity(new UrlEncodedFormEntity(nvps));
// Execute request
HttpResponse response = this.httpclient.execute(httpost);
//Check response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("entity " + slurp(entity.getContent(), 10000000));
System.out.println("entity " + response.getStatusLine().getStatusCode());
return true;
}
return false;
}
public boolean sendSMS(String toMobile,String message) throws IOException {
HttpPost httpost = new HttpPost(SEND_SMS_URL);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("MobileNos", toMobile));
nvps.add(new BasicNameValuePair("Message", message));
httpost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = this.httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
if(entity != null) {
System.out.println("entity " + slurp(entity.getContent(), 10000000));
System.out.println("entity " + response.getStatusLine().getStatusCode());
return true;
}
return false;
}
public boolean logoutSMS() throws IOException {
HttpGet httpGet = new HttpGet(LOGOUT_URL);
HttpResponse response;
response = this.httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out
.println("entity " + slurp(entity.getContent(), 10000000));
System.out.println("entity "
+ response.getStatusLine().getStatusCode());
return true;
}
return false;
}
public static String slurp(final InputStream is, final int bufferSize)
{
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (;;) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
}
finally {
in.close();
}
}
catch (UnsupportedEncodingException ex) {
/* ... */
}
catch (IOException ex) {
/* ... */
}
return out.toString();
}
/**
* #param args
*/
public static void main(String[] args) {
//Replace DEMO_USERNAME with username of your account
String username = "********";
//Replace DEMO_PASSWORD with password of your account
String password = "****";
//Replace TARGET_MOBILE with a valid mobile number
String toMobile = "****";
String toMessage = "Hello";
Mobiletry2 sMS = new Mobiletry2(username, password);
try{
if(sMS .isLoggedIn() && sMS .sendSMS(toMobile,toMessage))
{
sMS.logoutSMS();
System.out.println("Message was sent successfully " );
}
}
catch(IOException e)
{
System.out.println("Unable to send message, possible cause: " + e.getMessage());
}
}
}
Then go through the sms providing API the web service that u are using .They must be providing any alternate for over come this issue.Captcha is used for preventing automated submissions on any site .
Captcha code is generated at runtime, so it is not possible to predefine the captcha code in your application,thats the reason captcha is comes into the picture to prevent automation submissions on any site.
Related
I have a server and a client that sends requests. I don't need to identify the requests when it works in synch mode. But in asynch mode each request must have an identificator, so I could be sure that the response corresponds to exact request. The server is not to be updated, I have to put the identificator in the client's code. Is there a way do do it? I can't find out any.
Here is my main class. I guess all must be clear, the class is very simple.
public class MainAPITest {
private static int userId = 0;
private final static int NUM_OF_THREADS = 10;
private final static int NUM_OF_USERS = 1000;
public static void main(String[] args) {
Security.addProvider(new GammaTechProvider());
ExecutorService threadsExecutor = Executors.newFixedThreadPool(NUM_OF_THREADS);
for (int i = 0; i < NUM_OF_USERS; i++) {
MyRunnable user = new MyRunnable();
userId++;
user.uId = userId;
threadsExecutor.execute(user);
}
threadsExecutor.shutdown();
}
}
class MyRunnable implements Runnable {
int uId;
#Override
public void run() {
try {
abstrUser user = new abstrUser();
user.setUserId(uId);
user.registerUser();
user.chooseAndImplementTests();
user.revokeUser();
} catch (Exception e) {
e.printStackTrace();
}
}
}
User class describes the user's behaviour. It is long enough, idk if it is needed here. User runs a number of random tests. Each test has its own class that extends abstract test class, where the http connection is established:
import org.json.JSONObject;
import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public abstract class abstractRESTAPITest {
protected String apiUrl;
public abstractRESTAPITest() {
}
protected byte[] sendRequest(JSONObject jsonObject) throws IOException {
return this.sendRequest(jsonObject, (String) null, (String) null);
}
protected byte[] sendRequest(JSONObject jsonObject, String username, String password) throws IOException {
HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(this.apiUrl)).openConnection();
if (username != null && password != null) {
String userPassword = username + ":" + password;
httpURLConnection.setRequestProperty("Authorization", "Basic " + DatatypeConverter.printBase64Binary(userPassword.getBytes()));
}
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoOutput(true);
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write(jsonObject.toString().getBytes());
dataOutputStream.flush();
System.out.println("REST send: " + jsonObject.toString());
if (httpURLConnection.getResponseCode() != 200) {
System.out.println("REST send error, http code " + httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
throw new IOException();
} else {
byte[] responseBody = null;
StringBuilder data = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
data.append(line);
responseBody = data.toString().getBytes();
}
if (br != null) {
br.close();
}
return responseBody;
}
}
public abstract boolean test();
}
Now I am trying to transform the httpUrlConnection part of the code into a kind of this.
Jsonb jsonb = JsonbBuilder.create();
var client = HttpClient.newHttpClient();
var httpRequest = HttpRequest.newBuilder()
.uri(new URI(apiUrl))
.version(HttpClient.Version.HTTP_2)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonb.toJson(jsonObject)))
.build();
client.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());
It must send a JSON request and receive JSON response. HttpClient, introduced in Java11, has sendAsync native method, so I try to use it. But I don't understand fully how it works, so I have no success.
I'm developing a application to view list view.But There is runtime error
This is my code. There are codes files and exception error that I got in run time.
package com.example.official2.xoxo.activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.official2.xoxo.R;
import com.example.official2.xoxo.app.Config;
import com.example.official2.xoxo.helper.JSONParser;
import com.example.official2.xoxo.helper.JsonWebToken;
import com.example.official2.xoxo.helper.SQLiteHandler;
import com.example.official2.xoxo.helper.ServiceHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Products extends AppCompatActivity{
private String TAG = Products.class.getSimpleName();
//Call the config class to get the url
public Config con = new Config();
private String url_details = con.getAllProducts();
//ArrayOption-->Array Adapter--> ListView
//List View:(Views: productlist.xml)
private ListView lv;
private ProgressDialog pDialog;
// CustomListAdapter adapter;
JSONParser jsonParser = new JSONParser();
ServiceHandler sh;
ArrayList<HashMap<String, String>> productList;
// URL to get contacts JSON
private static String url = "http://uat.fxhello.com/api/shop/products";
JsonWebToken jsonWebToken;
//JSON NODE NAMES
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "payload";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "product_name";
private static final String TAG_PRICE = "price";
private static final String TAG_PIC = "profileimage";
private SQLiteHandler db;
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
productList = new ArrayList<>();
lv = (ListView) findViewById(R.id.listViewProducts);
jsonWebToken = new JsonWebToken();
// String tok = jsonWebToken.getDefaults(getContext());
String tok = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE3MDcsImlzcyI6Imh0dHA6XC9cL3VhdC5meGhlbGxvLmNvbVwvYXBpXC9hdXRoZW50aWNhdGUiLCJpYXQiOjE0ODIzNDMzMDMsImV4cCI6MTQ4MjQyOTcwMywibmJmIjoxNDgyMzQzMzAzLCJqdGkiOiI3NGQ5ZGIwNTA3NDc2NDAwNzc2MmYzODJiNGQxZmU4MCJ9.LF2Q8KUD7hoFjBJ4fsNjYS8rCzCevsZ4g0jukBK0lj0";
Log.d("Responsetoken", tok);
new Getproduct().execute();
//populateListView();
}
/**
* Async task class to get json by making HTTP call
*/
private class Getproduct extends AsyncTask<String, Void, JSONObject> {
private JSONObject json;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(Products.this);
//pDialog.setMessage("Loading Contacts. Please wait...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
}
protected JSONObject doInBackground(String... args) {
String userID = args[0];
sh = new ServiceHandler(userID);
String jsondata = sh.makeServiceCall(url_details, ServiceHandler.POST, null);
// JSONObject json = jsonParser.makeHttpRequest(url_details,"GET");
System.out.println("jsondata" + jsondata);
if (jsondata != null)
Log.d("Create Response", jsondata);
else {
Toast.makeText(Products.this.getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
try {
json = new JSONObject(jsondata);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(JSONObject s) {
// dismiss the dialog after getting all products
// pDialog.dismiss();
System.out.println(productList);
try {
JSONArray products = json.getJSONArray(TAG_PRODUCT);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//Storing each json item in a variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// String image = c.getString(TAG_PIC);
//tmp hash map for single contact
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to HashMap => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
// map.put(TAG_PIC,image);
productList.add(map);
// adding contact to contact list
productList.add(map);
// Dismiss the progress dialog
//if (pDialog.isShowing())
// pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
Products.this, productList,
R.layout.productlist, new String[]{TAG_ID, TAG_NAME,
TAG_PRICE}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
}
}
ServiceHandler class file. I used this code to get data to products from service handler
package com.example.official2.xoxo.helper;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Created by Official 2 on 12/19/2016.
*/
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
private String token;
private String refresh_url = "application/vnd.fxhello.v1+json";
public ServiceHandler() {
}
public ServiceHandler(String token) {
this.token = token;
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
String tok = token;
Log.d("Responsetoken", tok);
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization","Bearer "+tok);
httpGet.setHeader("Accept", refresh_url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
public String makeADDCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
String tok = token;
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Authorization","Bearer "+tok);
httpPost.setHeader("Accept", refresh_url);
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
String tok = token;
Log.d("Responsetoken", tok);
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization",tok);
httpGet.setHeader("Accept", refresh_url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
I got this as error
FATAL EXCEPTION: AsyncTask #1
Process: com.example.official2.xoxo, PID: 30695
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:97)
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:95)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
This are the server side values---------------------------
enter image description here
Your contacts JsonArray is null.
for (int i = 0; i < contacts.length(); i++) {}
Should be
JSONArray products = json.getJSONArray(TAG_PRODUCT)
for (int i = 0; i < products.length(); i++) {}
I think the Toast in doInBackground method is causing the problem ... because in this method you cannot communicate with UI thread... PreExecute and PostExecute methods can do.
Your stacktrace links to:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:97)
at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:95)
Which corresponds with this line: String userID = args[0];
This line is an array, which explains ArrayIndexOutOfBoundsException
And it is due to this:
new Getproduct().execute();
You never pass any arguments in when you initialize getproduct, so the array index is 0 an as such causing the exception
I am posting data by this POST method or by the first answer to this question, posting the data to a spring servlet configured with:
#RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String insert(String a) {
The servlet-method is called, but its parameter 'a' is null. Why?
Edit: The main method and the AsyncTask:
main method
ServerCaller serverCaller = new ServerCaller();
try {
serverCaller.execute(new URL("http://192.168.56.1:8080/SpringHibernateExample/insert"));
}
AsyncTask
package com.test.insert;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
public class ServerCaller extends AsyncTask<URL, Integer, Long> {
#Override
protected Long doInBackground(URL... params1) {
try {
POST(params1[0].toString());
}
catch (Exception e) {
Log.realException(e);
throw new RuntimeException(e);
}
return 22l;
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
public static String POST(String url) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "a");
jsonObject.accumulate("country", "b");
jsonObject.accumulate("twitter", "c");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
}
catch (Exception e) {
Log.e(e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
i think you pass a json object but you do not map it in spring.
In Spring you have to create a class ie CustomClass with properties name, country, twitter
public class CustomClass{
private String name;
private String country;
private String twitter;
//getters and setters should be here
}
then the code in Spring should look like this
#RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String insert(#RequestBody CustomClass cs) {
cs.getName();
Let me know if this helped
I have acutally a problem with my Android HTTPClient.
I want to send POST data to a website and parse the content after this.
My problem is, that the POST data wasn't sent to the webserver.
I don't know why.
Here is my HTTP Util Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class HTTPHelperUtil {
private static HTTPHelperUtil instance;
private String url;
private List<NameValuePair> nameValuePairs;
private String result;
private HTTPHelperUtil() {
// nothing to do
}
public synchronized static HTTPHelperUtil getInstance() {
if (HTTPHelperUtil.instance == null) {
HTTPHelperUtil.instance = new HTTPHelperUtil();
}
return HTTPHelperUtil.instance;
}
public HTTPHelperUtil init(String url, List<NameValuePair> nameValuePairs) {
this.url = url;
this.nameValuePairs = nameValuePairs;
return HTTPHelperUtil.instance;
}
public HTTPHelperUtil start() throws ClientProtocolException, IOException {
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
AsyncTask<List<NameValuePair>, Void, String> execute = sendPostReqAsyncTask.execute(nameValuePairs);
return HTTPHelperUtil.instance;
}
class SendPostReqAsyncTask extends AsyncTask<List<NameValuePair>, Void, String> {
#Override
protected String doInBackground(List<NameValuePair>... params) {
String res = "";
List<NameValuePair> postPairs = params[0];
System.out.println(postPairs.get(0));
System.out.println(postPairs.get(1));
if (postPairs != null && !postPairs.isEmpty()) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(postPairs));
HttpResponse response;
response = httpclient.execute(httppost);
if (response != null && response.getEntity() != null) {
InputStream content = response.getEntity().getContent();
if (content != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(content, "UTF-8"));
while (true) {
String addingSource = reader.readLine();
if (addingSource != null) {
res = addingSource;
break;
}
}
}
}
} catch (IllegalStateException e) {
return "-";
} catch (IOException e) {
return "-";
}
}
System.out.println(res);
return res;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
HTTPHelperUtil.this.result = result;
}
}
public String getResult() {
System.out.println("Result = " + result);
return result;
}
}
There is the call from my Activity:
final String url = "http://example.com/app/mysite.php";
List<NameValuePair> postParams = new ArrayList<NameValuePair>(2);
postParams.add(new BasicNameValuePair("username", username));
postParams.add(new BasicNameValuePair("password", password));
HTTPHelperUtil.getInstance().init(url, postParams);
String result = "";
try {
HTTPHelperUtil.getInstance().start();
result = HTTPHelperUtil.getInstance().getResult();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My test-page doesn't get the username and password via POST.
Does anyone see the mistake in my code?
Thanks
As per your code :
List postParams = new ArrayList (2);
Here you are passing 2 in the constructor which is not required while declaring the list with name value pair.
This might be the reason as rest all code seems fine.
I have a PNR Inquiry app on Google Play. It was working very fine. But recently Indian Railwys added captcha to their PNR Inquiry section and because of this I am not able to pass proper data to the server to get proper response. How to add this captcha in my app in form of an imageview and ask the users to enter captcha details also so that I can send proper data and get proper response.
Indian Railways PNR Inquiry Link
Here is my PnrCheck.java which I was using earlier. Please help what modifications should be done here..
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
public class PNRStatusCheck {
public static void main(String args[]) {
try {
String pnr1 = "1154177041";
String reqStr = "lccp_pnrno1=" + pnr1 + "&submitpnr=Get+Status";
PNRStatusCheck check = new PNRStatusCheck();
StringBuffer data = check.getPNRResponse(reqStr, "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi");
if(data != null) {
#SuppressWarnings("unused")
PNRStatus pnr = check.parseHtml(data);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public StringBuffer getPNRResponse(String reqStr, String urlAddr) throws Exception {
String urlHost = null;
int port;
String method = null;
try {
URL url = new URL(urlAddr);
urlHost = url.getHost();
port = url.getPort();
method = url.getFile();
// validate port
if(port == -1) {
port = url.getDefaultPort();
}
} catch(Exception e) {
e.printStackTrace();
throw new Exception(e);
}
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost(urlHost, port);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
#SuppressWarnings("unused")
String resData = null;
#SuppressWarnings("unused")
String statusStr = null;
StringBuffer buff = new StringBuffer();
try {
String REQ_METHOD = method;
String[] targets = { REQ_METHOD };
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", targets[i]);
req.setEntity(new InputStreamEntity(new ByteArrayInputStream(reqStr.toString().getBytes()), reqStr.length()));
req.setHeader("Content-Type", "application/x-www-form-urlencoded");
req.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7");
req.setHeader("Cache-Control", "max-age=0");
req.setHeader("Connection", "keep-alive");
req.setHeader("Origin", "http://www.indianrail.gov.in");
req.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
req.setHeader("Referer", "http://www.indianrail.gov.in/pnr_Enq.html");
//req.setHeader("Accept-Encoding", "gzip,deflate,sdch");
req.setHeader("Accept-Language", "en-US,en;q=0.8");
req.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
httpexecutor.preProcess(req, httpproc, context);
HttpResponse response = httpexecutor.execute(req, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
Header[] headers = response.getAllHeaders();
for(int j=0; j<headers.length; j++) {
if(headers[j].getName().equalsIgnoreCase("ERROR_MSG")) {
resData = EntityUtils.toString(response.getEntity());
}
}
statusStr = response.getStatusLine().toString();
InputStream in = response.getEntity().getContent();
BufferedReader reader = null;
if(in != null) {
reader = new BufferedReader(new InputStreamReader(in));
}
String line = null;
while((line = reader.readLine()) != null) {
buff.append(line + "\n");
}
try {
in.close();
} catch (Exception e) {}
}
} catch (Exception e) {
throw new Exception(e);
} finally {
try {
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return buff;
}
public PNRStatus parseHtml(StringBuffer data) throws Exception {
BufferedReader reader = null;
if(data != null) {
reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data.toString().getBytes())));
} else {
return null;
}
String line = null;
TrainDetails trainDetails = new TrainDetails();
List<PassengerDetails> passDetailsList = new ArrayList<PassengerDetails>();
PassengerDetails passDetails = null;
int i = 0;
while ((line = reader.readLine()) != null) {
if(line.startsWith("<TD") && line.contains("table_border_both")) {
line = line.replace("<B>", "");
line = line.substring(line.indexOf("\">")+2, line.indexOf("</")).trim();
if(line.contains("CHART")) {
trainDetails.setChatStatus(line);
break;
}
if(i > 7) {//Passenger Details
if(passDetails == null) {
passDetails = new PassengerDetails();
}
switch(i) {
case 8 :
passDetails.setName(line);
break;
case 9 :
passDetails.setBookingStatus(line.replace(" ", ""));
break;
case 10 :
passDetails.setCurrentStatus(line.replace(" ", ""));
i = 7;
break;
}
if(i == 7 ) {
passDetailsList.add(passDetails);
passDetails = null;
}
} else { // Train details
switch(i){
case 0 :
trainDetails.setNumber(line);
break;
case 1 :
trainDetails.setName(line);
break;
case 2 :
trainDetails.setBoardingDate(line);
break;
case 3 :
trainDetails.setFrom(line);
break;
case 4 :
trainDetails.setTo(line);
break;
case 5 :
trainDetails.setReservedUpto(line);
break;
case 6 :
trainDetails.setBoardingPoint(line);
break;
case 7 :
trainDetails.setReservedType(line);
break;
default :
break;
}
}
i++;
}
}
if(trainDetails.getNumber() != null) {
PNRStatus pnrStatus = new PNRStatus();
pnrStatus.setTrainDetails(trainDetails);
pnrStatus.setPassengerDetails(passDetailsList);
return pnrStatus;
} else {
return null;
}
}
}
If you right click on that page and see the source on http://www.indianrail.gov.in/pnr_Enq.html, you'll find the source of function that generates the captcha, compare the captcha and validates it:
There is a javascript function hat draws the captcha:
//Generates the captcha function that draws the captcha
function DrawCaptcha()
{
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
}
//Function to checking the form inputs:
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){ //here validating the captcha
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
Also instead of using URL http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi, try URL: http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi_28688.cgi . The previous one is down. I think it has been changed.
Hope this helps you.
I found this answer on one post asking same:
If you check the html code, its actualy pretty bad captcha. Background of captcha is: http://www.indianrail.gov.in/1.jpg Those numbers are actualy in input tag:
What they are doing is, via javascript, use numbers from that hidden input tag and put them on that span with "captcha" background.
So basicaly your flow is:
read their html
get "captcha" (lol, funny captcha though) value from input field
when user puts data in your PNR field and presses Get Status
post form field, put PNR in proper value, put captcha in proper value
parse response
Oh yeah, one more thing. You can put any value in hidden input and "captcha" input, as long as they are the same. They aren't checking it via session or anything.
EDIT (code sample for submiting form): To simplify posting form i recommend HttpClient components from Apache: http://hc.apache.org/downloads.cgi Lets say you downloaded HttpClient 4.3.1. Include client, core and mime libraries in your project (copy to libs folder, right click on project, properties, Java Build Path, Libraries, Add Jars -> add those 3.).
Code example would be:
private static final String FORM_TARGET = "http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi.cgi";
private static final String INPUT_PNR = "lccp_pnrno1";
private static final String INPUT_CAPTCHA = "lccp_capinp_val";
private static final String INPUT_CAPTCHA_HIDDEN = "lccp_cap_val";
private void getHtml(String userPnr) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(INPUT_PNR, userPnr); // users PNR code
builder.addTextBody(INPUT_CAPTCHA, "123456");
builder.addTextBody("submit", "Get Status");
builder.addTextBody(INPUT_CAPTCHA_HIDDEN, "123456"); // values don't
// matter as
// long as they
// are the same
HttpEntity entity = builder.build();
HttpPost httpPost = new HttpPost(FORM_TARGET);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
String htmlString = "";
try {
response = client.execute(httpPost);
htmlString = convertStreamToString(response.getEntity().getContent());
// now you can parse this string to get data you require.
} catch (Exception letsIgnoreItForNow) {
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException ignoredOnceMore) {
} finally {
try {
is.close();
} catch (IOException manyIgnoredExceptions) {
}
}
return sb.toString();
}
Also, be warned i didn't wrap this in AsyncTask call, so you will have to do that.