Reputation: 847
I am trying to send an image from android client to servlet. I am using JSON to send encoded image and decoding in servlet.
When I run the servlet in eclipse I get 'null' on tomcat server console. And the same response is given when I tried to put printf statements for testing.
My servlet cose is:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
try
{
res.setContentType("application/json");
res.setHeader("Cache-Control", "nocache");
res.setCharacterEncoding("utf-8");
PrintWriter out = res.getWriter();
JSONObject json = new JSONObject();
String jsonString = json.getString("image");
byte[] decodedString = Base64.decodeBase64(jsonString.getBytes());//, Base64.DEFAULT);
FileOutputStream fos = new FileOutputStream("C:\\Users\\OWNER\\Desktop\\image.jpg");
try {
fos.write(decodedString);
}
finally {
fos.close();
}
// finally output the JSON with 1 for success
JSONObject response=new JSONObject();
out.println(response.put("result", 1).toString());
}
catch(Exception e){e.printStackTrace();}
}
The android code is:
class ImageUploadTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(URL);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
HttpEntity res;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Compress to jpg and convert to byte[]:
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String imgData= Base64.encodeToString(data, Base64.DEFAULT);
String img=imgData.replace("\n", "%20");
//add fields in JSON:
JSONObject jsonObject= new JSONObject();
jsonObject.put("img",data);
httpPost.setEntity(new ByteArrayEntity(jsonObject.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
@Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("result");
if (success == 1) {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
caption.setText("");
} else {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
web.xml:
<servlet>
<servlet-name>q</servlet-name>
<servlet-class>Server1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>q</servlet-name>
<url-pattern>/P4</url-pattern>
</servlet-mapping>
After launching app on android device, when upload button is pressed, there is no response. On the tomcat server I get 'null'.
How can I make this work? Thank you!
Upvotes: 0
Views: 161
Reputation: 2508
If your client side works right:
You should create json object base on request:
BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
String jsonStr = "";
if(br != null)
jsonStr = br.readLine();
JSONObject json = new JSONObject(jsonStr);
Use img
instead of image
:
String jsonString = json.getString("img");
Edit: To debug your program at first write a simple example: a servlet that just return a simple json result. Test this servlet by firebug and firefox. Then add an android program that just call this servlet. If this simple program works right,then add other aspect of your program step by step and test your program at each step.
Upvotes: 1