HTTPClient doesn't send HttpPost request - java

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.

Related

Why this error come FATAL EXCEPTION: AsyncTask #1

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

Calling a spring controller with POST in android result in a null parameter

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

The method is undefined by the type HttpUtil

I'm new with android programming and I have been fallowing a tutorial to get a live twitter feed in my app. I have been getting the fallowing error "The method getHttpResponse(HttpGet) is undefined by the type HttpUtil" on my String twitterTweets = httpUtil.getHttpResponse(httpGet) and httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
Any help would be appreciated thanks.
My Code is as fallows
package com.javapapers.social.twitter;
import android.util.Base64;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.javapapers.java.io.HttpUtil;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
public class TwitterAPI {
private String twitterApiKey;
private String twitterAPISecret;
final static String TWITTER_TOKEN_URL = "https://api.twitter.com/oauth2/token";
final static String TWITTER_STREAM_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
public TwitterAPI(String twitterAPIKey, String twitterApiSecret){
this.twitterApiKey = twitterAPIKey;
this.twitterAPISecret = twitterApiSecret;
}
public ArrayList<TwitterTweet> getTwitterTweets(String screenName) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
try {
String twitterUrlApiKey = URLEncoder.encode(twitterApiKey, "UTF-8");
String twitterUrlApiSecret = URLEncoder.encode(twitterAPISecret, "UTF-8");
String twitterKeySecret = twitterUrlApiKey + ":" + twitterUrlApiSecret;
String twitterKeyBase64 = Base64.encodeToString(twitterKeySecret.getBytes(), Base64.NO_WRAP);
TwitterAuthToken twitterAuthToken = getTwitterAuthToken(twitterKeyBase64);
twitterTweetArrayList = getTwitterTweets(screenName, twitterAuthToken);
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return twitterTweetArrayList;
}
public ArrayList<TwitterTweet> getTwitterTweets(String screenName,
TwitterAuthToken twitterAuthToken) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
if (twitterAuthToken != null && twitterAuthToken.token_type.equals("bearer")) {
HttpGet httpGet = new HttpGet(TWITTER_STREAM_URL + screenName);
httpGet.setHeader("Authorization", "Bearer " + twitterAuthToken.access_token);
httpGet.setHeader("Content-Type", "application/json");
HttpUtil httpUtil = new HttpUtil();
String twitterTweets = httpUtil.getHttpResponse(httpGet);
twitterTweetArrayList = convertJsonToTwitterTweet(twitterTweets);
}
return twitterTweetArrayList;
}
public TwitterAuthToken getTwitterAuthToken(String twitterKeyBase64) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(TWITTER_TOKEN_URL);
httpPost.setHeader("Authorization", "Basic " + twitterKeyBase64);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
HttpUtil httpUtil = new HttpUtil();
String twitterJsonResponse = httpUtil.getHttpResponse(httpPost);
return convertJsonToTwitterAuthToken(twitterJsonResponse);
}
private TwitterAuthToken convertJsonToTwitterAuthToken(String jsonAuth) {
TwitterAuthToken twitterAuthToken = null;
if (jsonAuth != null && jsonAuth.length() > 0) {
try {
Gson gson = new Gson();
twitterAuthToken = gson.fromJson(jsonAuth, TwitterAuthToken.class);
} catch (IllegalStateException ex) { }
}
return twitterAuthToken;
}
private ArrayList<TwitterTweet> convertJsonToTwitterTweet(String twitterTweets) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
if (twitterTweets != null && twitterTweets.length() > 0) {
try {
Gson gson = new Gson();
twitterTweetArrayList =
gson.fromJson(twitterTweets, new TypeToken<ArrayList<TwitterTweet>>(){}.getType());
} catch (IllegalStateException e) {
}
}
return twitterTweetArrayList;
}
private class TwitterAuthToken {
String token_type;
String access_token;
}
}
I assume you are following this tutorial (http://javapapers.com/android/android-twitter-feed-reader/).
Scroll further down to find the sourcecode for HttpUtil.

POST JSON to webservice

I'm trying to connect to a web service and post JSON using this code but i don't know what im doing wrong. [edit]I wrote the same class using HTTPClient and it worked but since httpURLConnect is what google focuses on, I changed it to work with that.
The question is, am I sending properly formatted json? and is the way im sending it to the server the right way? I've marked the problem area
This is the helper class I'm using to connect and post the json:
package com.example.connecttohtml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;
public class HtmlHelper {
public static JSONArray getData(RequestPackage p){
JSONArray jsonArray;
BufferedReader readData = null;
String uri = p.getUri();
if(p.getMethod().equals("GET")){
uri += "?" + p.getEncodedParams();
}
try{
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(p.getMethod());
conn.setRequestProperty("Content-Type", "application/json");
Log.d("getParams", p.getEncodedParams().toString());
JSONObject json = new JSONObject(p.getParams());
String params = json.toString();
////THIS IS THE PART IM NOT SURE OF///////////////////////
if (p.getMethod().equals("POST")){
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
Log.d("jsonPassed", params);
writer.write(params);
writer.flush();
}
//////////////////////////////////////END///////
StringBuilder sb = new StringBuilder();
readData = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = readData.readLine()) != null){
sb.append(line + "\n");
}
jsonArray = new JSONArray(sb.toString());
return jsonArray;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
if(readData !=null){
try {
readData.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
This is the RequestPackage class implementation code:
package com.example.connecttohtml;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class RequestPackage {
private String uri;
private String method = "GET";
private Map<String, String> params = new HashMap<String, String>();
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value){
params.put(key, value);
}
public String getEncodedParams(){
StringBuilder sb = new StringBuilder();
for(String key : params.keySet()){
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(sb.length()> 0 ){
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}//getEncodedParams
}

How to send an SMS programmatically using java?

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.

Categories