java http 传输二进制流_文件以二进制流POST的HTTP请求

/**

* 描述:文件以二进制流POST的HTTP请求

*

* @param reqUrl

*            HTTP请求URL

* @param fileUrl

*            文件地址

* @return HTTP响应的字符串

* @throws Exception

*/

public static String doPostFile(String reqUrl, String fileUrl) {

return doPostFile(reqUrl, fileUrl, ENCODEING);

}

private static String doPostFile(String reqUrl, String fileUrl, String encoding) {

HttpURLConnection url_con = null;

String responseContent = null;

try {

URL url = new URL(reqUrl);

url_con = (HttpURLConnection) url.openConnection();

url_con.setRequestMethod("POST");

url_con.setConnectTimeout(CONNECTTIMEOUT);

url_con.setDoOutput(true);

url_con.setRequestProperty("Content-type","application/x-java-serialized-object");

File file = new File(fileUrl);

InputStream ins = new FileInputStream(file);

byte[] data = IOUtils.toByteArray(ins);

url_con.getOutputStream().write(data, 0, data.length);

url_con.getOutputStream().flush();

url_con.getOutputStream().close();

InputStream in = url_con.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(in,

ENCODEING));

String tempLine = rd.readLine();

StringBuffer tempStr = new StringBuffer();

String crlf = System.getProperty("line.separator");

while (tempLine != null) {

tempStr.append(tempLine);

tempStr.append(crlf);

tempLine = rd.readLine();

}

responseContent = tempStr.toString();

rd.close();

in.close();

} catch (IOException e) {

System.err.println("网络故障");

logger.info("--------------------->网络故障");

} finally {

if (url_con != null) {

url_con.disconnect();

}

}

return responseContent;

}

}


版权声明:本文为weixin_35911221原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。