Java入門–ウェブサーバーにファイルをPOSTする方法

Javaコード:
public static String doPostFile(String reqUrl, String fileUrl) {
return doPostFile(reqUrl, fileUrl, ENCODEING);
}

private static String doPostFile(String reqUrl, String fileUrl, String encoding) {
HttpURLConnection urlcont = null;
String responseContent = null;
try {
URL url = new URL(reqUrl);

urlcont = (HttpURLConnection) url.openConnection();
urlcont.setRequestMethod(“POST");
urlcont.setConnectTimeout(CONNECTTIMEOUT);
urlcont.setDoOutput(true);
urlcont.setRequestProperty(“Content-type","application/x-java-serialized-object");

File file = new File(fileUrl);
InputStream ins = new FileInputStream(file);
byte[] data = IOUtils.toByteArray(ins);

urlcont.getOutputStream().write(data, 0, data.length);
urlcont.getOutputStream().flush();
urlcont.getOutputStream().close();

InputStream in = urlcont.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 (urlcont != null) {
urlcont.disconnect();
}
}
return responseContent;
}
}

Java

Posted by arkgame