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
Related
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 am trying to parse JSON, I have done it there before but not quiet this way. I spent hours trying to solve the problem, but I dont know what is wrong with the code.I am attaching the entire code for the activity, Web Request class and the layout. Any help will be greatly appreciated.
I get this error
java.io.FileNotFoundException: /data/system/users/sdp_engine_list.xml: open failed: ENOENT (No such file or directory)
05-19 18:17:27.427 3450-3450/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
05-19 18:17:28.232 3450-3592/? W/DisplayManagerService: Failed to notify process 20004 that displays changed, assuming it died.
This is the activity Transactions class.
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import com.rectuca.iyzicodemo.Classes.Transaction;
import com.rectuca.iyzicodemo.Library.WebRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Transactions extends ListActivity {
// URL to get contacts JSON
private static String url = "http://www.mocky.io/v2/573dbd243700005f194dcdcc";
// JSON Node names
private static final String TAG_PAYMENTS= "payments";
private static final String TAG_PAYMENT_ID = "paymentId";
private static final String TAG_SENT_BY = "sentBy";
private static final String TAG_DATE_TIME = "dateTime";
private static final String TAG_SENT_TO = "sentTo";
private static final String TAG_BANK_NAME = "bankName";
private static final String TAG_INSTALLMENTS = "installments";
private static final String TAG_AMOUNT = "amount";
private static final String TAG_3DS = "threeDs";
private static final String TAG_CANCELLED = "cancelled";
private static final String TAG_RETURNED = "returned";
private static final String TAG_TRANSACTION_STATUS = "transactionStatus";
private static final String TAG_BLOCKAGE_AMOUNT = "blockage_amount";
private static final String TAG_BLOCKAGE_RELEASE_DATE = "blockageReleaseDate";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
// Calling async task to get json
new GetInfo().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetInfo extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> transactionInfoList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(Transactions.this);
proDialog.setMessage("Please Wait...");
proDialog.setCancelable(false);
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webReq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webReq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
transactionInfoList = ParseJSON(jsonStr);
return null;
}
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
transactionInfoList=new ArrayList<HashMap<String, String>>();
ListAdapter adapter = new SimpleAdapter(
Transactions.this, transactionInfoList,
R.layout.row_layout, new String[]{TAG_SENT_TO,TAG_DATE_TIME
,TAG_BANK_NAME,TAG_AMOUNT,TAG_3DS, TAG_CANCELLED,
TAG_RETURNED},
new int[]{R.id.name,R.id.dateTime ,R.id.bankName,R.id.amount,
R.id.threeDS, R.id.cancelled, R.id.returned});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> paymentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray payments = jsonObj.getJSONArray(TAG_PAYMENTS);
// looping through All Payments
for (int i = 0; i < payments.length(); i++) {
JSONObject c = payments.getJSONObject(i);
String dateTime =c.getString(TAG_DATE_TIME);
String sentTo =c.getString(TAG_SENT_TO);
String bankName =c.getString(TAG_BANK_NAME)+" ( "+c.getString(TAG_INSTALLMENTS)+" ) " ;
String amount =c.getString(TAG_AMOUNT);
String threeDS =c.getString(TAG_3DS);
String cancelled =c.getString(TAG_CANCELLED);
String returned =c.getString(TAG_RETURNED);
// temporary hashmap for a single payment
HashMap<String, String> payment = new HashMap<String, String>();
// adding every child node to HashMap key => value
payment.put(TAG_DATE_TIME, dateTime);
payment.put(TAG_SENT_TO, sentTo);
payment.put(TAG_BANK_NAME, bankName);
payment.put(TAG_AMOUNT, amount);
payment.put(TAG_3DS, threeDS);
payment.put(TAG_CANCELLED, cancelled);
payment.put(TAG_RETURNED, returned);
// adding student to students list
paymentList.add(payment);
}
return paymentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
This is the WebRequest Class
package com.rectuca.iyzicodemo.Library;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class WebRequest {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* #url - url to make request
* #requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* #url - url to make request
* #requestmethod - http request method
* #params - http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
This is what I am trying to do
http://lh3.googleusercontent.com/JqcySZU2Pz067NutlDvPP5Zq_3n_WSAllIuEdjQjOjyeGkKguaMNCrltaKbjBCi16g=h900-rw
I would suggest you to use
VOLLEY networking library by google
You should try to use Volley JSONOBJECTREQUEST() and you won't have any issue after that parsing will be easier.
add this to dependency section of your app
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
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
}
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 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.