日期:2014-05-20  浏览次数:20687 次

关于模拟http post 图片文件时,出现的问题
主要代码如下:  
int   port   =   80;  
String   host   =   "test.lingye.com ";  
Socket   clientSocket;  
clientSocket   =   new   Socket(InetAddress.getByName(host),port);  

File   pic_file   =   new   File( "1.jpg ");  
String   pic_file_string   =   readFileAsString(pic_file.toString());  

DataOutputStream   outbound   =   new   DataOutputStream(   clientSocket.getOutputStream()   );  
DataInputStream   inbound   =   new   DataInputStream(   clientSocket.getInputStream()   );  

String   pic_file_string_encode   =   URLEncoder.encode(pic_file_string);  

String   message   =   "POST   /test.php   HTTP/1.1   \r\n "  
+   "Host:   test.lingye.com   \r\n "  
+   "Accept:   */*   \r\n "  
+   "Cache-Control:no-cache   \r\n "  
+   "User-Agent:   MSIE6.0;   \r\n "  
+   "Content-Type:   application/x-www-form-urlencoded   \r\n "  
+   "Content-Length:   "   +   pic_file_string_encode.length()   +   "   \r\n "  
+   "Connection:   Close   \r\n\r\n "  
+   "&pic_file= "   +   pic_file_string_encode   +   "   \r\n ";  
byte   pic_bytes[]   =   message.getBytes();  

outbound.flush();;  
outbound.write(pic_bytes);  

outbound.close();  
inbound.close();  
clientSocket.close();  

程序post数据到test.php接收保存。  
当post其他类型如文本文件时,是没有问题的,但是post图片文件时,php端接收的数据跟原文件比较起来好像丢失了部分,图片不能正常显示。  
不知道上面代码的发送方式对不对呢?难道图片文件和普通的其他文件处理方式不一样吗?  


------解决方案--------------------
为什么要这么写??
不是直接有HTTP类的??


------解决方案--------------------
outbound.flush();;
outbound.write(pic_bytes);
把上面两行的顺序颠倒一下吧,我怀疑,图片文件的最后读取的数据没有写过去。
因为你把flush放在write前面了!!!嘎嘎!!!
------解决方案--------------------
建议你先把
outbound.flush();;
这句注释掉。
如果还不行的话看看是不是
Content-Length: " + pic_file_string_encode.length()
设置长度错误