Android simulates hybrid form submission data (two methods). Java hybrid form submission

Source: Internet
Author: User

Recently I was working on a project similar to a mobile phone for everyone. After I wrote it in the background, I used JSP and the jar package used was smartupload. It is estimated that Java Web users should know about this.

Then I tested it normally on the Web. Then I took out the code I wrote some time ago and found that it was useless. I don't know what the situation is, however, I think my code is okay. The only difference from the previous Code is that the background uses fileupload, but I don't think it should be affected, the following code can be used to submit text data. The image data cannot be submitted. However, the previous project can be submitted. After one day, we finally developed a suitable method.

1. Previous Code (I think the code is okay. This code can be used to submit text data. I don't know why the image data cannot be submitted, but no error is reported .) The Code has no comments. If you do not understand it, ask me. If someone knows why the Code cannot submit the form data, thank you for pointing out that I have thanked you first.

/*** Imitate the form to post all message to the URL *** @ author administrator Wang yuchao * @ Param strurl * @ Param allparams * @ Param fileparam * @ return receive the All message that service machine response to you * Based on The param 'strurl' * @ throws exception */Public String submitform (string strurl, hashmap <string, string> allparams, hashmap <string, File> fileparam) throws exception {string Boundary = Java. util. UUID. randomuuid (). tostring (); string prefix = "--", linend = "\ r \ n"; string multipart_from_data = "multipart/form-Data"; string charset = "UTF-8 "; URL url = new URL (strurl); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setreadtimeout (5*1000); Conn. setdoinput (true); Conn. setdooutput (true); Conn. setusecaches (false); Conn. setinstancefollowredirects (true); // redirect Conn. set Requestmethod ("Post"); Conn. setrequestproperty ("connection", "keep-alive"); Conn. setrequestproperty ("charsert", "UTF-8"); Conn. setrequestproperty ("Content-Type", multipart_from_data + "; boundary =" + boundary); Conn. connect (); // upload the text content to stringbuilder strallparams = new stringbuilder (); For (map. entry <string, string> param: allparams. entryset () {strallparams. append (prefix); strallparams. append (Boundary); ST Rallparams. append (linend); strallparams. append ("content-Disposition: Form-data; name = \" "+ Param. getkey () + "\" "+ linend); strallparams. append ("Content-Type: text/plain; charset =" + charset + linend); strallparams. append ("content-transfer-encoding: 8bit" + linend); strallparams. append (linend ). append (Param. getvalue ()). append (linend);} dataoutputstream = new dataoutputstream (Conn. getoutpu Tstream (); dataoutputstream. Write (strallparams. tostring (). getbytes (); // upload the file content if (fileparam! = NULL) {for (map. entry <string, File> file: fileparam. entryset () {system. out. println (file. getkey (); system. out. println (file. getvalue (); stringbuilder strfileparam = new stringbuilder (); strfileparam. append (prefix); strfileparam. append (Boundary); strfileparam. append (linend); strfileparam. append ("content-Disposition: Form-data; name = \" messagecontentpic \ "; filename = \" "+ file. getkey () + "\" "+ linend); ST Rfileparam. append ("Content-Type: Application/octet-stream; charset =" + charset + linend); strfileparam. append (linend); dataoutputstream. write (strfileparam. tostring (). getbytes (); inputstream input = new fileinputstream (file. getvalue (); byte [] buffer = new byte [1024*5]; int Len = 0; while (LEN = input. read (buffer ))! =-1) {dataoutputstream. write (buffer, 0, Len);} input. close (); dataoutputstream. write (linend. getbytes () ;}} byte [] enddata = NULL; If (fileparam! = NULL) {enddata = (prefix + boundary + prefix + linend ). getbytes ();} else {enddata = (prefix + boundary + prefix ). getbytes ();} dataoutputstream. write (enddata); dataoutputstream. flush (); int responsecode = Conn. getresponsecode (); stringbuilder result = new stringbuilder (); system. out. println ("response code:" + responsecode); If (responsecode = 200) {bufferedreader = new bufferedreader (New inputstre Amreader (conn. getinputstream (); string Readline = ""; while (Readline = bufferedreader. Readline ())! = NULL) {result. append (Readline) ;}bufferedreader. Close () ;}dataoutputstream. Close (); Conn. Disconnect (); return result. tostring ();}

2. Go to the topic. Today, after a long time, I finally got a picture to submit. It's very boring. Three jar files are required. Can go to my resources page download, free: http://download.csdn.net/my

Commons-httpclient.jar ------------------- commons-logging.jar -------------------- commons-codec-1.5.jar ------------------------ is where the error is reported, is less which jar package, then download on line.

This has a small problem, % E6 % 88% E6 % 91% af % E7 % 8e % 8B % E7 % 8e % 98% E8 % B6 % 89% EF % BC % 8C % E8 % BF % 99% E6 % 98% af % E6 % 88% 91httputil2% E7 % 9A % 84% E4 % B8 % 80% E4 % B8 % Aa % E6 % B5 % 8B % E8 % AF % 95. It should be a type of Chinese character encoding. There are various problems. I think it is very boring, don't want to get it, paste files.

Import Java. io. bufferedreader; import Java. io. file; import Java. io. inputstreamreader; import java.net. urlencoder; import Org. apache. commons. httpclient. httpclient; import Org. apache. commons. httpclient. methods. postmethod; import Org. apache. commons. httpclient. methods. multipart. filepart; import Org. apache. commons. httpclient. methods. multipart. multipartrequestentity; import Org. apache. commons. httpclient. methods. Multipart. part; import Org. apache. commons. httpclient. methods. multipart. stringpart; public class httputil2 {public static void main (string [] ARGs) throws exception {file F = new file ("D:/sk.png "); postmethod filepost = new postmethod ("********************************* * ***** write your own URL "); part [] parts = {New filepart ("FILENAME", F), new stringpart ("Account", "04101055"), new stringpart ("collegeid", "3728 "), new Stringpart ("messagekind", "0"), new stringpart ("messagecontenttext", urlencoder. encode ("I'm Wang yuchao, this is a test of my httputil2", "UTF-8")}; filepost. setrequestentity (New multipartrequestentity (parts, filepost. getparams (); httpclient clients = new httpclient (); int status = clients.exe cutemethod (filepost); try {bufferedreader RD = new bufferedreader (New inputstreamreader (filepost. getresponsebodyasstream (), "UTF-8" ); Stringbuffer = new stringbuffer (); string line; while (line = RD. Readline ())! = NULL) {stringbuffer. append (line);} Rd. close (); system. out. println ("the received stream is:" + stringbuffer + "--" + status);} catch (exception e) {Throw new runtimeexception ("error ", e );}}}

Which of the following is a better solution? Let's talk to your friends.

I just solved the problem.

New stringpart ("messagecontenttext", urlencoder. encode ("Wang yuchao", "UTF-8"); pass all parameter values in byte type, also decode

The server can write another sentence. Inbound and Downlink

Urldecoder. Decode ("request. geparamter (" name ")", "UTF-8"); then it turns back,

No matter how the Server accepts the data, it must transcode the accepted data. If the data is normal, it will not be transferred. If it is not normal, it will be transcoded, this helps prevent unexpected situations.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.