Sunday, January 26, 2014

android upload files to the server through socket and returns data, Jia! ! !


            
To the great God is this, I want to upload on android through the socket to a file and some relevant data to the server, and then I after the server receives the data and processing is complete needs to android client to return some of the corresponding data, these data PrintWriter out = request.getWriter () object to print. How do I receive the data on the client side ah?

This is the client sends the file method:
public static boolean postFileUseSocket (String path, Map params, FormFile [] files) throws Exception {
final String BOUNDARY = "--------------------------- 7da2137580612"; / / data separator
final String endline = "-" + BOUNDARY + "- \ r \ n" ;/ / end of data marker

int fileDataLength = 0;
The total length of
{/ / get the file types of data: for (files FormFile uploadFile)StringBuilder fileExplain = new StringBuilder ();
fileExplain.append ("-");
fileExplain.append (BOUNDARY);
fileExplain.append ("\ r \ n") ;/ / ----------------------------- 7da2137580612
fileExplain.append ("Content-Disposition: form-data; name = \" "+ uploadFile.getParameterName () +" \ "; filename = \" "+ uploadFile.getFilname () +" \ "\ r \ n") ;
fileExplain.append ("Content-Type:" + uploadFile.getContentType () + "\ r \ n \ r \ n");
fileExplain.append ("\ r \ n");
fileDataLength + = fileExplain.length ();
if (uploadFile.getInStream ()! = null) {
fileDataLength + = uploadFile.getFile () length ();.
} Else {
. fileDataLength + = uploadFile.getData () length;
}
}
StringBuilder textEntity = new StringBuilder ();
for (Map.Entry entry: params.entrySet ()) {/ / Entity Data
constructed text type parametertextEntity.append ("-");
textEntity.append (BOUNDARY);
textEntity.append ("\ r \ n");
textEntity.append ("Content-Disposition: form-data; name = \" "+ entry.getKey () +" \ "\ r \ n \ r \ n");
textEntity.append (entry.getValue ());
textEntity.append ("\ r \ n");
}
Total Entity Data / / calculate the length of the transmission to the server
.. int dataLength = textEntity.toString () getBytes () length + fileDataLength + endline.getBytes () length;.

URL url = new URL (path);






int port = url.getPort () == -1 80: url.getPort ();
?Socket socket = new Socket (InetAddress.getByName (url.getHost ()), port);
/ / Socket.setKeepAlive (true);
OutputStream outStream = socket.getOutputStream ();
/ / The following completion of the HTTP request header sent
String requestmethod = "POST" + url.getPath () + "HTTP/1.1 \ r \ n";
outStream.write (requestmethod.getBytes ());
String accept = "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 ";
outStream.write (accept.getBytes ());
String language = "Accept-Language: zh-CN \ r \ n";
outStream.write (language.getBytes ());
String contenttype = "Content-Type: multipart / form-data; boundary =" + BOUNDARY + "\ r \ n";
outStream.write (contenttype.getBytes ());
String contentlength = "Content-Length:" + dataLength + "\ r \ n";
outStream.write (contentlength.getBytes ());
String alive = "Connection: Keep-Alive \ r \ n";
outStream.write (alive.getBytes ());
String host = "Host:" + url.getHost () + ":" + port + "\ r \ n";
outStream.write (host.getBytes ());
/ / Finished after the HTTP request header to write a carriage return line feed
according to the HTTP protocoloutStream.write ("\ r \ n" getBytes ().);
/ / Send data from all types of text entities out
outStream.write (textEntity.toString () getBytes ().);
/ / Send data from all file types entity out
for (FormFile uploadFile: files) {
StringBuilder fileEntity = new StringBuilder ();
fileEntity.append ("-");
fileEntity.append (BOUNDARY);
fileEntity.append ("\ r \ n");
fileEntity.append ("Content-Disposition: form-data; name = \" "+ uploadFile.getParameterName () +" \ "; filename = \" "+ uploadFile.getFilname () +" \ "\ r \ n") ;
fileEntity.append ("Content-Type:" + uploadFile.getContentType () + "\ r \ n \ r \ n");
outStream.write (fileEntity.toString () getBytes ().);
if (uploadFile.getInStream ()! = null) {
byte [] buffer = new byte [1024];
int len ​​= 0;
while ((len = uploadFile.getInStream (). read (buffer, 0, 1024))! = -1) {
outStream.write (buffer, 0, len);
}
uploadFile.getInStream () close ();.
} Else {
outStream.write (uploadFile.getData (), 0, uploadFile.getData () length.);
}
outStream.write ("\ r \ n" getBytes ().);
}
/ / Send data following the end of the sign, which means that the data has ended
outStream.write (endline.getBytes ());



BufferedReader reader = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
String result = reader.readLine ();
if (result.indexOf ("200") == -1) {/ / read data returned by the web server to determine whether the request code 200, if not 200, on behalf of the request fails

return false;
}
/ / Log.i ("reponse", line);
outStream.flush ();
outStream.close ();
reader.close ();
socket.close ();
return true;
}

This is the code that the client receives the data and returns the results:

public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/ / Get file for factory
FileItemFactory factory = new DiskFileItemFactory ();
/ / Get file upload Servlet object
ServletFileUpload upload = new ServletFileUpload (factory);

response.setContentType ("text / html");
PrintWriter out = response.getWriter ();

UploadFileDao dao = new UploadFileDaoImpl ();
UploadFile uf = new UploadFile ();
String tempPath = "";
UserDao udao = new UserDaoImpl ();
boolean mark = false;
try {
/ / Parse request
List items = upload.parseRequest (request);
Iterator iter = items.iterator ();
/ / Iterate Files domain
while (iter.hasNext ()) {
FileItem item = (FileItem) iter.next ();
/ / Determine an ordinary text field
if (item.isFormField ()) {
String fieldName = item.getFieldName ();
if (fieldName.toLowerCase (). equals ("uploadtime")) {
uf.setUploadTime (new String (item.getString (). getBytes (
"Iso-8859-1"), "utf-8"));

}

if (fieldName.toLowerCase (). equals ("audiodesc")) {
uf.setFileDesc (new String (item.getString (). getBytes (
"Iso-8859-1"), "utf-8"));
}
if (fieldName.toLowerCase (). equals ("audioname")) {
uf.setFileName (new String (item.getString (). getBytes (
"Iso-8859-1"), "utf-8"));
}
if (fieldName.toLowerCase (). equals ("audiouploadpersoncode")) {
uf.setUploadPersonCode (new String (item.getString ()
. GetBytes ("iso-8859-1"), "utf-8"));
}

} Else {
/ / Determine the file domain
String fullFileName = item.getName ();
int idx = fullFileName.lastIndexOf (".");
String subfix = fullFileName.substring (idx);
String dateStr = new Date () getTime () + "";.
String fileName = dateStr + subfix;

uf.setCode (dateStr);
String path = this.getServletContext (). GetRealPath (
"\ \ Audio");

File f = new File (path + "\ \" + fileName);
System.out.println (path);
tempPath = path + "\ \" + fileName;
File dir = new File (path);
if (! dir.exists ()) {
dir.mkdirs ();
}
uf.setFilePath (tempPath);
User user = udao.queryIsExist (uf.getUploadPersonCode ());
if (user! = null) {

mark = dao.saveAudio (uf);
item.write (f);
if (mark) {
out.print ("1");
} Else {
out.print ("0");
}
} Else {
out.print ("2");
}

}
}

} Catch (Exception e) {
e.printStackTrace ();
out.print ("0");
}

out.flush ();
out.close ();
}


You help me see how big God get ah! Thank you very much!
Reply:
Here embarrassed doPost () method is a method of server Servlet
Reply:
How to fend for themselves, ah, the great God who see it!
Reply:
Tian Tian popularity
Reply:
Bangding, socket has been no contact, hope an early solution to the landlord
Reply:
Alas tangled up! Nobody birds.
Reply:
Client sent over the data directly read the socket on the line, read back the data may need to resolve their own, in fact, not as good as some of the more simple with httpclient
Reply:
I also encountered the same problem, still not resolved
Reply:
Will the landlord not solve ah?
Reply:
I also encountered the same problem, the landlord resolved, the possibility of sharing, the brother thanks!

No comments:

Post a Comment