文件上传问题
下面是我的文件上传功能的代码,不知道哪存在问题,一直上传不了,希望各位帮帮忙,谢谢
//实现文件上传
//参数1:服务的地址
//参数2:上传文件路径
protected String UploadFileStream(String strUrl,String SourceFilePath)
{
try {
URL url = new URL(strUrl);
try {
File file = new File(SourceFilePath);
FileInputStream fs = new FileInputStream(SourceFilePath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//参数设置
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
conn.connect();
//int i = conn.getResponseCode();//测试语句,每次到这i=200,但是这句一执行,os的close=true,后面就没办法写了,不解为什么会这样
byte[] buf = new byte[(int)file.length()];
if (fs != null)
{
int numRead = fs.read(buf);
if (numRead <= 0)
{
break;
}
else
{
os.write(buf);
}
}
int j = conn.getResponseCode();//这句是测试,每次到这的时候,j=400,中间只执行了os.write(buf);
os.flush();
os.close();
fs.close();
conn.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
return "上传失败";
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
return "上传失败";
}
return "上传成功";
}
问题就像上面描述得那样,这样程序执行没报错,但是没办法将数据发送到服务器。我的服务器是WCF,上传契约我在web里调试过,没什么问题,但是客户端要是安卓模拟机器上,就没办法收到数据,不知道为什么会这样,url地址没有错,希望各位高手帮我看看