Кода -копия выглядит следующим образом:
пакетные инструменты;
Импорт java.io.bufferedReader;
Импорт java.io.file;
импортировать java.io.fileinputstream;
Импорт java.io.filenotFoundException;
импортировать java.io.inputstream;
Импорт java.io.inputStreamReader;
импортировать java.io.outputstream;
импортировать java.net.inetaddress;
импортировать java.net.socket;
импортировать java.net.url;
импортировать java.util.map;
Import Android.util.log;
/**
* Загруженные файлы
*/
открытый класс FormFile {
Приватная окончательная статическая строка logkey = "formfile";
/** Загрузить данные файла*/
частный байт [] данные;
Private InputStream Instream;
Частный файл;
/** Имя файла*/
Private String FilmName;
/** Имя параметра запроса*/
Private String Parametername;
/** Тип контента*/
Private String ContentType = "Приложение/октет-поток";
/**
*
* @param filmname
* Имя файла
* @param данные
* Загруженные данные файла
* @param parametername
* Параметры
* @param contentType
* Тип контента
*/
Public FormFile (String FilmName, Byte [] Data, String Parametername,
String contentType) {
this.data = data;
this.filName = filmName;
this.parametername = parametername;
if (ContentType! = NULL)
this.contenttype = contentType;
}
/**
*
* @param filmname
* имя файла
* @param file
* Загруженные файлы
* @param parametername
* Параметры
* @param contentType
* Тип контента
*/
public formfile (String FilmName, файл файла, String ParameterName,
String contentType) {
this.filName = filmName;
this.parametername = parametername;
this.file = file;
пытаться {
this.intream = new FileInputStream (file);
} catch (filenotFoundException e) {
e.printstacktrace ();
}
if (ContentType! = NULL)
this.contenttype = contentType;
}
public file getFile () {
вернуть файл;
}
public inputStream getInstream () {
вернуть instrem;
}
public byte [] getData () {
вернуть данные;
}
public String getFilName () {
вернуть фильм;
}
public void setFilName (String filmName) {
this.filName = filmName;
}
public String getParameterName () {
возврат параметрического имени;
}
public void setParametername (String parametername) {
this.parametername = parametername;
}
public String getContentType () {
вернуть ContentType;
}
public void setContentType (String contentType) {
this.contenttype = contentType;
}
Private String Operatype = null;
public void setoper (string operatype) {
this.opertype = opertype;
}
Публичный логический пост (путь строки, карта <string, string> params)
бросает исключение {
Final String Bound = "------------------ 7DA2137580612";
Окончательная строка Endline = "-" + Boundary + "-/r/n"; // Флаг конечных данных
int filedatalength = 0;
// Получить общую длину данных типа файла
StringBuilder fileExplain = new StringBuilder ();
fileExplain.append ("-");
fileExplain.append (граница);
fileexplain.append ("/r/n");
fileExplain.append ("Контент-дискуссия: form-data; name =/" "
+ getParameterName () + "/"; filename =/"" + getFilName ()
+ "/"/r/n ");
fileExplain.append ("content-type:" + getContentType () + "/r/n/r/n");
fileexplain.append ("/r/n");
filedatalength += fileExplain.length ();
if (getInStream ()! = null) {
FileDatalength += getFile (). Length ();
} еще {
filedatalength += getData ().
}
StringBuilder Textentity = new StringBuilder ();
for (map.Entry <string, string> entry: params.EntrySet ()) {// Создание данных объекта параметров типа текста
Textentity.append ("-");
Textentity.append (граница);
textentity.append ("/r/n");
Textentity.append ("Disposition: Form-Data; name =/" "
+ entry.getKey () + "/"/r/n/r/n ");
Textentity.append (entry.getValue ());
textentity.append ("/r/n");
}
Log.v (logkey, textentity.tostring ());
// Вычисление общей длины данных объекта, передаваемых на сервер
int dataLength = textentity.toString (). getBytes (). Длина
+ filedatalength + endline.getbytes (). Length;
Url url = new URL (путь);
Log.v (logkey, url.tostring ());
int port = url.getport () == -1? 80: url.getport ();
Сокет сокет = новый сокет (inetAddress.getByName (url.gethost ()), port);
OutputStream outstream = socket.getOutputStream ();
// заголовок HTTP -запроса отправлен ниже
String requestMethod = "post" + url.getPath () + "?" + Opertype + "http/1.1/r/n";
Log.v (logkey, requestmethod);
upstream.write (requestmethod.getbytes ());
String Accept = "Принять: Image/GIF, Image/JPEG, Image/PJPEG, Image/PJPEG, Application/X-Shockwave-Flash, Application/XAML+XML, Application/Vnd.MS-XPSDOCUMENT, Application/X-MS- XBAP, Application/X-MS-Application, Application/Vnd.MS-Excel, Application/Vnd.MS-PowerPoint, Application/Msword, */ */r/n »;
upstream.write (Accept.getBytes ());
String language = "Принятие языка: zh-cn/r/n";
upstream.write (language.getbytes ());
String contentType = "content-type: multipart/form-data; boundary ="
+ Граница + "/r/n";
upstream.write (contentType.getBytes ());
String contentLength = "content-length:" + dataLength + "/r/n";
upstream.write (contentlength.getbytes ());
String alive = "connection: Keep-alive/r/n";
upstream.write (alive.getbytes ());
String host = "host:" + url.gethost () + ":" + port + "/r/n";
upstream.write (host.getbytes ());
// После написания заголовка HTTP -запроса напишите возврат перевозки и разрыв линии в соответствии с протоколом HTTP
upstream.write ("/r/n" .getbytes ());
// Отправлять все данные объекта типа текста
upstream.write (textentity.toString (). GetBytes ());
// отправлять данные объекта всех типов файлов
StringBuilder fileEntity = new StringBuilder ();
fileEntity.append ("-");
fileEntity.append (граница);
fileEntity.append ("/r/n");
fileEntity.append ("Disposition: Form-Data; name =/" "
+ getParameterName () + "/"; filename =/"" + getFilName ()
+ "/"/r/n ");
fileEntity.append ("content-type:" + getContentType () + "/r/n/r/n");
upstream.write (fileEntity.toString (). getBytes ());
if (getInStream ()! = null) {
Byte [] buffer = новый байт [1024];
int len = 0;
while ((len = getInstream (). Read (Buffer, 0, 1024))! = -1) {
upstream.write (буфер, 0, Лен);
}
GetInStream (). Close ();
} еще {
upstream.write (getData (), 0, getData (). Length);
}
upstream.write ("/r/n" .getbytes ());
// флаг конечного значения данных отправляется ниже, чтобы указать, что данные закончились
upstream.write (endline.getbytes ());
BufferedReader Reader = New BufferedReader (New InputStreamReader (socket.getInputStream ()));
if (reader.readline (). indexof ("200") == -1) {// Читать данные, возвращаемые веб -сервером, и определить, составляет ли код запроса 200. Если он не 200, это означает, что запрос неуспешный
вернуть ложь;
}
upstream.flush ();
outstream.close ();
reader.close ();
Socket.Close ();
вернуть истину;
}
}
// тестовый код
File iconfile = new File ("pail path");
String url = "htttp: //192.168.1.101: 8080/app/initservlet";
Map <string, string> map = new hashmap <string, string> (); // Содержимое формы
map.put ("name", "blog");
if (iconfile! = null) {
Formfile uploadfile = new FormFile (iconfile.getName (),
Iconfile, "Iconfile", "Image/jpeg");
uploadfile.setoper ("action = insertusr"); // insert? action = insertusr на URL
пытаться {
Boolean isok = uploadfile.post (url, map);
} catch (Exception e) {
// Todo Auto Generated Catch Blach
e.printstacktrace ();
}