This example shares the specific code for Android to upload file data through HTTP protocol for your reference. The specific content is as follows
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; public class SocketHttpRequester { /** * Send xml data * @param path Request address * @param xml xml data * @param encoding * @return * @throws Exception */ public static byte[] postXml(String path, String xml, String encoding) throws Exception{ byte[] data = (encoding); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)(); ("POST"); (true); ("Content-Type", "text/xml; charset="+ encoding); ("Content-Length", ()); (5 * 1000); OutputStream outStream = (); (data); (); (); if(()==200){ return readStream(()); } return null; } /** * Submit data directly to the server through the HTTP protocol, realizing the form submission function as follows: * <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/" enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT TYPE="text" NAME="id"> <input type="file" name="imagefile"/> <input type="file" name="zip"/> </FORM> * @param path upload path (Note: Avoid using path tests like localhost or 127.0.0.1, because it will point to the mobile emulator, you can use path tests like http://192.168.1.10:8080) * @param params Request parameter key is the parameter name and value is the parameter value * @param file Upload file */ public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{ final String BOUNDARY = "---------------------------7da2137580612"; //Data Divider Line final String endline = "--" + BOUNDARY + "--\r\n";//Data end flag int fileDataLength = 0; for(FormFile uploadFile : files){//Get the total length of file type data StringBuilder fileExplain = new StringBuilder(); ("--"); (BOUNDARY); ("\r\n"); ("Content-Disposition: form-data;name=\""+ ()+"\";filename=\""+ () + "\"\r\n"); ("Content-Type: "+ ()+"\r\n\r\n"); ("\r\n"); fileDataLength += (); if(()!=null){ fileDataLength += ().length(); }else{ fileDataLength += ().length; } } StringBuilder textEntity = new StringBuilder(); for (<String, String> entry : ()) {//Construct the entity data of text type parameters ("--"); (BOUNDARY); ("\r\n"); ("Content-Disposition: form-data; name=\""+ () + "\"\r\n\r\n"); (()); ("\r\n"); } //Calculate the total length of entity data transmitted to the server int dataLength = ().getBytes().length + fileDataLength + ().length; URL url = new URL(path); int port = ()==-1 ? 80 : (); Socket socket = new Socket((()), port); OutputStream outStream = (); //The following completes the sending of the HTTP request header String requestmethod = "POST "+ ()+" HTTP/1.1\r\n"; (()); String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/-excel, application/-powerpoint, application/msword, */*\r\n"; (()); String language = "Accept-Language: zh-CN\r\n"; (()); String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n"; (()); String contentlength = "Content-Length: "+ dataLength + "\r\n"; (()); String alive = "Connection: Keep-Alive\r\n"; (()); String host = "Host: "+ () +":"+ port +"\r\n"; (()); //After writing the HTTP request header, write a carriage return and line break according to the HTTP protocol. ("\r\n".getBytes()); //Send all text type entity data out (().getBytes()); //Send all file types entity data for(FormFile uploadFile : files){ StringBuilder fileEntity = new StringBuilder(); ("--"); (BOUNDARY); ("\r\n"); ("Content-Disposition: form-data;name=\""+ ()+"\";filename=\""+ () + "\"\r\n"); ("Content-Type: "+ ()+"\r\n\r\n"); (().getBytes()); if(()!=null){ byte[] buffer = new byte[1024]; int len = 0; while((len = ().read(buffer, 0, 1024))!=-1){ (buffer, 0, len); } ().close(); }else{ ((), 0, ().length); } ("\r\n".getBytes()); } //The data end flag is sent below to indicate that the data has ended (()); BufferedReader reader = new BufferedReader(new InputStreamReader(())); if(().indexOf("200")==-1){//Read the data returned by the web server and determine whether the request code is 200. If it is not 200, it means that the request failed. return false; } (); (); (); (); return true; } /** * Submit data to the server * @param path upload path (Note: Avoid using path tests like localhost or 127.0.0.1, because it will point to the mobile emulator, you can use path tests like http://192.168.1.10:8080) * @param params Request parameter key is the parameter name and value is the parameter value * @param file Upload file */ public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{ return post(path, params, new FormFile[]{file}); } /** * Submit data to the server * @param path upload path (Note: Avoid using path tests like localhost or 127.0.0.1, because it will point to the mobile emulator, you can use path tests like http://192.168.1.10:8080) * @param params Request parameter key is the parameter name and value is the parameter value * @param encode encoding */ public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode) throws Exception{ List<NameValuePair> formparams = new ArrayList<NameValuePair>();// Used to store request parameters for(<String, String> entry : ()){ (new BasicNameValuePair((), ())); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode); HttpPost httppost = new HttpPost(path); (entity); HttpClient httpclient = new DefaultHttpClient();//Think of as a browser HttpResponse response = (httppost);//Send a post request return readStream(().getContent()); } /** * Send a request * @param path Request path * @param params Request parameter key is parameter name value is parameter value * @param encode The encoding of the request parameters */ public static byte[] post(String path, Map<String, String> params, String encode) throws Exception{ //String params = "method=save&name="+ ("Laobi", "UTF-8")+ "&age=28&";// Parameters that need to be sent StringBuilder parambuilder = new StringBuilder(""); if(params!=null && !()){ for(<String, String> entry : ()){ (()).append("=") .append(((), encode)).append("&"); } (()-1); } byte[] data = ().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)(); (true);//Allow external sending of request parameters (false);//No cache (5 * 1000); ("POST"); //The following sets the http request header ("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/-excel, application/-powerpoint, application/msword, */*"); ("Accept-Language", "zh-CN"); ("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); ("Content-Type", "application/x-www-form-urlencoded"); ("Content-Length", ()); ("Connection", "Keep-Alive"); //Send parameters DataOutputStream outStream = new DataOutputStream(()); (data);//Send parameters (); (); if(()==200){ return readStream(()); } return null; } /** * Read stream * @param inStream * @return byte array * @throws Exception */ public static byte[] readStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while( (len=(buffer)) != -1){ (buffer, 0, len); } (); (); return (); } }
package ; import ; import ; import ; import ; /** * Upload file */ public class FormFile { /* Upload file data */ private byte[] data; private InputStream inStream; private File file; /* File name */ private String filname; /* Request parameter name*/ private String parameterName; /* Content Type */ private String contentType = "application/octet-stream"; public FormFile(String filname, byte[] data, String parameterName, String contentType) { = data; = filname; = parameterName; if(contentType!=null) = contentType; } public FormFile(String filname, File file, String parameterName, String contentType) { = filname; = parameterName; = file; try { = new FileInputStream(file); } catch (FileNotFoundException e) { (); } if(contentType!=null) = contentType; } public File getFile() { return file; } public InputStream getInStream() { return inStream; } public byte[] getData() { return data; } public String getFilname() { return filname; } public void setFilname(String filname) { = filname; } public String getParameterName() { return parameterName; } public void setParameterName(String parameterName) { = parameterName; } public String getContentType() { return contentType; } public void setContentType(String contentType) { = contentType; } }
package ; import ; import ; public class StreamTool { /** * Read data from the input stream * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = (buffer)) !=-1 ){ (buffer, 0, len); } (); (); return (); } }
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private EditText timelengthText; private EditText titleText; private EditText videoText; @Override public void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(); Button button = (Button) (); timelengthText = (EditText) (); videoText = (EditText) (); titleText = (EditText) (); (new () { @Override public void onClick(View v) { String title = ().toString(); String timelength = ().toString(); Map<String, String> params = new HashMap<String, String>(); ("method", "save"); ("title", title); ("timelength", timelength); try { // ("http://192.168.1.100:8080/videoweb/video/", params, "UTF-8"); File uploadFile = new File((), ().toString()); FormFile formfile = new FormFile("02.mp3", uploadFile, "video", "audio/mpeg"); ("http://192.168.1.100:8080/videoweb/video/", params, formfile); (, , 1).show(); } catch (Exception e) { (, , 1).show(); (TAG, ()); } } }); } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.