String urlToConnect = "http://example.com/upload";
String paramToSend = "fubar";
File fileToUpload = new File("/path/to/file.txt");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"paramToSend\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
writer.println(paramToSend);
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"file.txt\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
//응답메시지.
BufferedReader in = new BufferedReader( new InputStreamReader ( connection.getInputStream(), "UTF-8") );
StringBuffer sb = new StringBuffer();
String output = "";
while( ( output = in.readLine() ) != null )
{
if( !output.equals( "") )
{
sb.append( output.trim() );
}
}
in.close();
System.out.println( sb.toString() );
댓글 없음:
댓글 쓰기