客户端 :
public static String post( String actionUrl ,
Map < String , String > params , Map < String , File > files )
throws IOException
{
String BOUNDARY = java.util.UUID.randomUUID ( ).toString ( ) ;
String PREFIX = "--" , LINEND = "\r\n" ;
String MULTIPART_FROM_DATA = "multipart/form-data" ;
String CHARSET = "UTF-8" ;
URL uri = new URL ( actionUrl ) ;
HttpURLConnection conn = ( HttpURLConnection ) uri
.openConnection ( ) ;
conn.setReadTimeout ( 5 * 1000 ) ; // 缓存的最长时间
conn.setDoInput ( true ) ;// 允许输入
// conn.setDoOutput ( true ) ;// 允许输出
conn.setUseCaches ( false ) ; // 不允许使用缓存
conn.setRequestMethod ( "POST" ) ;
conn.setRequestProperty ( "connection" , "keep-alive" ) ;
conn.setRequestProperty ( "Charsert" , "UTF-8" ) ;
conn.setRequestProperty ( "Content-Type" , MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY ) ;
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder ( ) ;
for ( Map.Entry < String , String > entry : params.entrySet ( ) )
{
sb.append ( PREFIX ) ;
sb.append ( BOUNDARY ) ;
sb.append ( LINEND ) ;
sb.append ( "Content-Disposition: form-data; name=\""
+ entry.getKey ( ) + "\"" + LINEND ) ;
sb.append ( "Content-Type: text/plain; charset="
+ CHARSET + LINEND ) ;
sb.append ( "Content-Transfer-Encoding: 8bit" + LINEND ) ;
sb.append ( LINEND ) ;
sb.append ( entry.getValue ( ) ) ;
sb.append ( LINEND ) ;
}
DataOutputStream outStream = new DataOutputStream (
conn.getOutputStream ( ) ) ;
outStream.write ( sb.toString ( ).getBytes ( ) ) ;
// 发送文件数据
if ( files != null )
for ( Map.Entry < String , File > file : files.entrySet ( ) )
{
StringBuilder sb1 = new StringBuilder ( ) ;
sb1.append ( PREFIX ) ;
sb1.append ( BOUNDARY ) ;
sb1.append ( LINEND ) ;
sb1.append ( "Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getKey ( ) + "\"" + LINEND ) ;
sb1.append ( "Content-Type: application/octet-stream; charset="
+ CHARSET + LINEND ) ;
sb1.append ( LINEND ) ;
outStream.write ( sb1.toString ( ).getBytes ( ) ) ;
InputStream is = new FileInputStream (
file.getValue ( ) ) ;
byte [ ] buffer = new byte [ 1024 ] ;
int len = 0 ;
while ( ( len = is.read ( buffer ) ) != - 1 )
{
outStream.write ( buffer , 0 , len ) ;
}
is.close ( ) ;
outStream.write ( LINEND.getBytes ( ) ) ;
}
// 请求结束标志
byte [ ] end_data = ( PREFIX + BOUNDARY + PREFIX + LINEND )
.getBytes ( ) ;
outStream.write ( end_data ) ;
outStream.flush ( ) ;
// 得到响应码
int res = conn.getResponseCode ( ) ;
System.out.println("response code == " + res);
InputStream in = conn.getInputStream ( ) ;
if ( res == 200 )
{
int ch ;
StringBuilder sb2 = new StringBuilder ( ) ;
while ( ( ch = in.read ( ) ) != - 1 )
{
sb2.append ( ( char ) ch ) ;
}
System.out.println(sb2.toString());
}
outStream.close ( ) ;
conn.disconnect ( ) ;
return in.toString ( ) ;
}
}
class MyThread implements Runnable{
@Override
public void run() {
String actionUrl = "http://192.168.1.138:8090/bank/ReceiveFile";
Map < String , String > params = new HashMap < String , String > ( ) ;
Gson gson = new Gson();
Person p = new Person();
String jsonData = gson.toJson(p);
System.out.println(jsonData);
params.put ( "json" , jsonData) ;
Map < String , File > files = new HashMap < String , File > ( ) ;
files.put ( "front.png" , new File ( "/sdcard/pictures/front.png" ) ) ;
files.put ( "back.png" , new File ( "/sdcard/pictures/back.png" ) ) ;
files.put ( "witness.png" , new File ( "/sdcard/pictures/witness.png" ) ) ;
files.put ( "together.png" , new File ( "/sdcard/pictures/together.png" ) ) ;
try {
String result = MainActivity.post(actionUrl,params,files);
System.out.println("111111" + result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
服务器端 :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("googddd");
/*
ServletInputStream is = request.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
buffer.append(line);
}
System.out.println(buffer.toString());
*/
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
System.out.println(fieldname + "========" + fieldvalue);
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
String path = request.getRealPath("");
item.write(new File(path + "/" +filename ));
System.out.println(filename);
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
服务器端要添加几个包:
commons-fileupload-1.2.1.jar;
commons-io-1.3.2.jar;
servlet-api.jar