Passing a JSON object to servlet from android - java

I am uploading a file to server from my android application using the below code, and its working fine. now I want to pass a jsonobject also to servlet, I tried some way like
mpEntity.addPart("param",new StringBody(details.toString(),"text/plain",
Charset.forName("UTF-8")));
here the details is a JSON object, but its not working, so please help me to solve this.
this is my code(in android) for file uploading.
private class AsyncCaller extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
JSONObject obj=new JSONObject();
try {
obj.put("m1", "adad");
obj.put("m2", "adadad");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpPost httppost = new HttpPost(
"http://172.20.56.229:8084/AndroidTesting/UploadServlet");
File file = new File("/sdcard/CEA.txt");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFe = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFe);
httppost.setEntity(mpEntity);
System.out
.println("executing request " + httppost.getRequestLine());
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
httpclient.getConnectionManager().shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

Related

POST JSON data to server

I am working on POST JSON data to server. It is working fine with a tutorial this link but it is not working with this with some of the required data changes. Is there anything related to Javaservlet and PHP links , as the first link is designed using Javasevlet and the other is in PHP ?
public static String POST(String url)
{
InputStream inputStream = null;
String result = "";
try {
org.apache.http.client.HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(url);
String json = "";
JSONObject jsonObject=new JSONObject();
/*JSONArray jsonArray=jsonObject.getJSONArray("object");
JSONObject jsonObject2=jsonArray.getJSONObject(10);*/
jsonObject.putOpt("id",2);
jsonObject.putOpt("address","myaddress");
json=jsonObject.toString();
StringEntity se=new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse=httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// person = new PersonLocator();
// person.setAddresS(myLocationText.getText().toString());
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
Thanks for the help in advance

Can't translate Postman request to Java

I have a post request working successfully in Postman, but when I make the same request from my Android app, I get "Internal Server Error". Do you see any difference between these two requests?
Postman
Android App
class MakeRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://sample.com/test");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Authorization", getB64Auth("username", "password"));
try {
JSONObject identity = new JSONObject();
identity.put("type", "number");
identity.put("endpoint", "12345");
JSONObject options = new JSONObject();
options.put("num", "12345");
JSONObject body = new JSONObject();
body.put("identity", identity);
body.put("method", "test");
body.put("options", options);
StringEntity se = new StringEntity(body.toString());
httppost.setEntity(se);
} catch (IOException e) {
Log.d("IOException", e.toString());
} catch (JSONException e) {
Log.d("JSONException", e.toString());
}
try {
ResponseHandler handler = new BasicResponseHandler();
HttpResponse response = httpclient.execute(httppost);
Log.d("HttpResponse", handler.handleResponse(response).toString());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.d("IOException", e.toString());
}
return null;
}
private String getB64Auth (String key, String secret) {
String source=key+":"+secret;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
return ret;
}
}
Other thoughts/hints:
Authentication is working properly in the java code. I tried with wrong username & password, and I got "Invalid Authorization"
The JSON string is exactly the same as the one in postman. I printed body.toString(), copied and pasted into Postman, and the request worked fine in Postman.
you should change httppost.setHeader("Content-type", "application/json"); to httppost.setHeader("Content-type", "application/form-data"); or httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
this should solve your issue.

httpPost not working using asynctask - giving invalid index, size is 0 exception

In order to avoid executing the http relating things in the UI thread, i migrated my code inside asynctask, before that, it was working fine on versions before 3.0 -- however, after literally copy pasting the code inside asynctask, it started to giving the invalid index, size is 0 exception. Whenever I need to use the method I am applying the call --
new dataRetrievalViaAsyncTask().execute(url, null, null); --
Whats wrong down there ?
class dataRetrievalViaAsyncTask extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(String... f_url)
{
Log.i("tag", "inside doInBackground");
String url2 = f_url[0];
Log.i("tag", url2);
HttpClient httpclient = new DefaultHttpClient();
Log.i("tag", "done : HttpClient httpclient = new DefaultHttpClient();");
HttpPost httppost = new HttpPost(url2);
Log.i("tag", "done : HttpPost httppost = new HttpPost(url);");
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("tag", "done : httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));");
HttpResponse response = httpclient.execute(httppost);
Log.i("tag", "done : HttpResponse response = httpclient.execute(httppost);");
HttpEntity entity = response.getEntity();
Log.i("tag", "done : HttpEntity entity = response.getEntity();");
is = entity.getContent();
Log.i("tag", "after : is = entity.getContent();");
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
// convert response to string
return null;
}
protected void onPostExecute()
{
try
{
Log.i("tag","before : BufferedReader reader = new BufferedReader(new Inp");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
try
{
Log.i("tag", "before : jsons ");
jArray = new JSONArray(result);
JSONObject json_data = null;
Log.i("tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++)
{
json_data = jArray.getJSONObject(i);
uid = json_data.getInt("uid");
item1= json_data.getString("item1");
item2 = json_data.getString("item2");
item3 = json_data.getString("item3");
item4 = json_data.getString("item4");
item5 = json_data.getString("item5");
item6 = json_data.getString("item6");
favorited = json_data.getString("favorited");
currentList.add(new itemClass(uid, item1 item2)); //there is a constructor for this in the itemClass
itemClass toSendToOffline = new itemsClass(uid, item1, item2, item3, item4, item5, item6, favorited);
myDBHelper.insertFromOnlineToDBtoSendToOffline();
}
} catch (JSONException e1)
{
Toast.makeText(getBaseContext(), "Not Found", Toast.LENGTH_LONG).show();
} catch (ParseException e1)
{
e1.printStackTrace();
}
super.onPostExecute(null);
}
}
(mainly the code is stopping at --
HttpResponse response = httpclient.execute(httppost);
I can not see nameValuePairs variable initialized anywhere, which is actually causing problem.
class dataRetrievalViaAsyncTask extends AsyncTask<Void, Void, String>
{
String URL = "";
public dataRetrievalViaAsyncTask( String url )
{
URL = url;
}
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... f_url)
{
String result="";
try
{
result=fetchdataFromServer(URL);
}
catch (JSONException e)
{
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result)
{
// See your results as string //result
}
public JSONObject getJsonObjectToRequestToServer(String plid) throws JSONException
{
JSONObject parms = new JSONObject();
parms.put("user_id", "");
parms.put("app_key", "xyz");
parms.put("secret", "abc");
parms.put("token", "");
parms.put("playurl", "1");
parms.put("mode", "playlistdetail");
parms.put("playlist_id", plid);
return parms;
}
public String fetchdataFromServer(String url) throws JSONException
{
String stringresponce = null;
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
JSONObject parms = getJsonObjectToRequestToServer("1");
StringEntity se;
se = new StringEntity(parms.toString());
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
#SuppressWarnings("rawtypes")
ResponseHandler responseHandler = new BasicResponseHandler();
stringresponce = httpClient.execute(httpPost, responseHandler);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return stringresponce;
}
}
put this code in your code and pass arguments ass you need this is the way how i request to server and get json response as string from result variable pass arguments to your url as i passed by making json object then convert them to string
then execute like this............
dataRetrievalViaAsyncTask asyncTask=new dataRetrievalViaAsyncTask(Yoururl);
asyncTask.execute();
hope this will help if you have some issues please post here thanks......

Android - How to Download XML Files with Android 4.0?

I will Download XML File with Android 4.0 my old Code works at Android 2.3.3 here:
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
I must have an Example without DefaultHttpClient .
From Gingerbread (2.3) and up, the preferred method for retrieving HTTP data is HttpUrlConnection. You might wanna check this blog post for details. You may also want to check the Javadoc for HttpUrlConnection
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
your problem may be the "strict mode" here.
you have to do http requests with a thread or an AsyncTask.
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
//http request here
//return the response as string
}
#Override
protected void onPostExecute(String result) {
//set the the data you get
}
then:
new RequestTask().execute(yourHttpRequestString)

Android : JSON Parser with async task (GET and POST methods)

Just want to check whether this JSON Parser with async task is it correctly done? When I put this code into my Eclipse, this (method.equals("POST") was underline red. And it state that the 'method' cannot be solved. Any suggestion or help in this? Thank you.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String url=null;
List<NameValuePair> nvp=null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
BackGroundTask Task= new BackGroundTask(url, method, params);
try {
return Task.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity 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, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
You forgot to declare method property in your BackGroundTask class.
EDIT Like this:
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
String method = null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
this.method = method;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity 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, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
You need to set method as a class variable within BackGroundTask. You are passing it into the constructor but not going anything with it. Set it the same way you have done with url and postparams.

Categories

Resources