日期:2014-05-19  浏览次数:20666 次

HTTP POST 发送文件时收不到返回.
我用HttpURLConnection来模拟HTTP的POST请求,并在InputStream里面,发送文件.
本来想先描述问题的.可是模述不清,先上代码
发送的代码:

public static String postByte() {
byte[] param = ZhsqTestHttp.readFileByBytes("D:\\logs\\tmsInfoLog.log");
URL url = null;
HttpURLConnection httpURLConnection = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(POST_URL);
httpURLConnection = (HttpURLConnection) url.openConnection();

// 设置连接属性
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);

// 设置请求属性
httpURLConnection.setRequestProperty("Content-length", "" + param.length);
httpURLConnection.setRequestProperty("Content-Type", "application/octet-stream");
httpURLConnection.setRequestProperty("ID", "48XYHA8OVG5LNGAY9RRH97A6ESL9LNL5");

// 建立输出流,并写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(param);
outputStream.flush();
outputStream.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
String line = "";
while ((line = reader.readLine()) != null) {
//返回打印处
System.out.println(line);
}
reader.close();

} catch (Exception e) {
e.printStackTrace();
sb.append("0");

} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();

}
System.out.println(sb.toString());
return sb.toString();
}



服务器处理端:

public String answer(String ID,HttpServletRequest request)throws ParamException {
ResultProxy result = new ResultProxy();
result.setCodeAndMsg(MsgCodeInfo.SUSS);
if (StringHelper.isNullOrEmpty(ID)) {
result.setCodeAndMsg(MsgCodeInfo.PARA_NULL_OR_ERROR);
result.setMsg("actionID 或 status,"+result.getMsg());
return JSON.toJSONString(result);
}else{
this.writeLogFile(request,answerFile);
return "OK";
}
}


public String writeLogFile(HttpServletRequest request,String fileMd5){
try {

String fileName = DateHelper.getDateNumByNow() + DateHelper.getUUID()+".log";
String filepath = createDir();

InputStream inputStream = request.getInputStream();
FileOutputStream fos = new FileOutputStream(filepath+"/"+fileName);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
inputStream.close();
return fileName;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}


HTTP:输出方法:
public void outJSON(String str) {
//上线的时候,以JSON的方式进行传输.
try