android中模擬http協議表單上傳
阿新 • • 發佈:2019-01-07
轉自:http://helloandroid.iteye.com/blog/1183853
利用ie瀏覽器外掛httpwatch檢視form表單上傳時的資料封裝格式,然後照著這資料格式自己一步一步封裝
- packagecom.android.cist.network.form;
- importjava.io.DataOutputStream;
- importjava.io.InputStream;
- importjava.io.UnsupportedEncodingException;
- importjava.net.HttpURLConnection;
-
import
- importjava.net.URLEncoder;
- importjava.util.Iterator;
- importjava.util.Map;
- importjava.util.Set;
- publicclassHttpFormUtil{
- publicstaticStringpost(StringactionUrl,Map<String,String>params,FormFile[]files){
- try{
- StringenterNewline="\r\n";
- Stringfix="--";
-
Stringboundary="######"
- StringMULTIPART_FORM_DATA="multipart/form-data";
- URLurl=newURL(actionUrl);
- HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
- con.setDoInput(true);
- con.setDoOutput(true);
- con.setUseCaches(false);
- con.setRequestMethod("POST");
-
con.setRequestProperty("Connection","Keep-Alive"
- con.setRequestProperty("Accept","image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/x-shockwave-flash,application/msword,application/vnd.ms-excel,application/vnd.ms-powerpoint,*/*");
- con.setRequestProperty("Accept-Encoding","gzip,deflate");
- con.setRequestProperty("Charset","UTF-8");
- con.setRequestProperty("Content-Type",MULTIPART_FORM_DATA+";boundary="+boundary);
- DataOutputStreamds=newDataOutputStream(con.getOutputStream());
- Set<String>keySet=params.keySet();
- Iterator<String>it=keySet.iterator();
- while(it.hasNext()){
- Stringkey=it.next();
- Stringvalue=params.get(key);
- ds.writeBytes(fix+boundary+enterNewline);
- ds.writeBytes("Content-Disposition:form-data;"+"name=\""+key+"\""+enterNewline);
- ds.writeBytes(enterNewline);
- //ds.write(value.getBytes("UTF-8"));
- ds.writeBytes(value);//如果有中文亂碼,儲存改用上面的ds.writeBytes(enterNewline);那句程式碼
- ds.writeBytes(enterNewline);
- }
- if(files!=null&&files.length>0){
- ds.writeBytes(fix+boundary+enterNewline);
- ds.writeBytes("Content-Disposition:form-data;"+"name=\""+files[0].getFormname()+"\""+";filename=\""+files[0].getFilname()+"\""+enterNewline);
- ds.writeBytes(enterNewline);
- ds.write(files[0].getData());
- ds.writeBytes(enterNewline);
- }
- ds.writeBytes(fix+boundary+fix+enterNewline);
- ds.flush();
- InputStreamis=con.getInputStream();
- intch;
- StringBufferb=newStringBuffer();
- while((ch=is.read())!=-1){
- b.append((char)ch);
- }
- ds.close();
- returnb.toString().trim();
- }catch(Exceptione){
- thrownewRuntimeException(e);
- }
- }
- publicstaticStringencode(Stringurl){
- try{
- returnURLEncoder.encode(url,"UTF-8");
- }catch(UnsupportedEncodingExceptionex){
- returnurl;
- }
- }
- }