开发者

Send image(jpg) via HttpPost from Android to Servlet(WebServer)

I have an image sitting on my SDcard开发者_开发百科 (of type jpg) and I am trying to send the image via HttpPost to my servlet running on Apache Tomcat 7.0

So far I have google-ing the way to do this but I can't seem to find the perfect way.

Do any of you might have some suggestion or solution to this problem?

Thank you in advance, Sammy Stevan Djap


HttpClient is the class to use and there's a tutorial for it. See the section Using HTTP client, right after the pictures.

UPDATE
What follows is commentary on the tutorial example from Developerlife.com. A good thing about that example is that it demonstrates how to send various types of data by encoding one type into another. One can send any of the types used in that chain of data conversions, by starting at the point in the chain that matches the type of data to be sent:

Strings are put in a Hashtable which is written to an ObjectOutputStream which is backed by a ByteArrayOutputStream that gets converted into a ByteArray that is in turn converted into a ByteArrayEntity for transmission.

To send just a ByteArray, skip all the steps that occur before the data becomes a ByteArray. Jump in at line 26 where a ByteArray is created with toByteArray().

For sending other types do the following(as per the example):
Line 26: ByteArray, just use it to make a ByteArrayEntity
Line 26: ByteArrayOutputStream, convert it to a ByteArray
Line 24: ObjectOutputStreams: create them on ByteArrayOutputStreams
Line 25: Objects: Write Strings, Hashtables, etc to an ObjectOutputStream.

 1 /** this method is called in a non-"edt" thread */
 2 private void _doInBackgroundPost() {
 3   Log.i(getClass().getSimpleName(), "background task - start");
 4 
 5 
 6   Hashtable<String, String> map = new Hashtable();
 7   map.put("uid", uid);
 8   map.put("pwd", pwd);
 9 
10   try {
11     HttpParams params = new BasicHttpParams();
12 
13     // set params for connection...
14     HttpConnectionParams.setStaleCheckingEnabled(params, false);
15     HttpConnectionParams.setConnectionTimeout(params, NetworkConnectionTimeout_ms);
16     HttpConnectionParams.setSoTimeout(params, NetworkConnectionTimeout_ms);
17     DefaultHttpClient httpClient = new DefaultHttpClient(params);
18 
19     // create post method
20     HttpPost postMethod = new HttpPost(LoginServiceUri);
21 
22     // create request entity
23     ByteArrayOutputStream baos = new ByteArrayOutputStream();
24     ObjectOutputStream oos = new ObjectOutputStream(baos);
25     oos.writeObject(map);
26     ByteArrayEntity req_entity = new ByteArrayEntity(baos.toByteArray());
27     req_entity.setContentType(MIMETypeConstantsIF.BINARY_TYPE);
28 


I have done this in a little bit cleaner way but with asp.net 'web form'. I am sure someone can easily do a makeover of that in servlet. You can find my solution here.

cheers

Fahar

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜