我需要从运行在Google App Engine中的Java Web 应用程序向MediaFire REST API发送HTTP POST 请求,以便上传文件。
请在此处查看上传功能文档(几行)。
查看文档和一些研究,我编写了以下 Java 代码来发出相应的请求:
byte[] bytesData = //byte array with file data
URL url = new URL("http://www.mediafire.com/api/upload/upload.php?" +
"session_token=" + sessionToken);
//Configure connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setReadTimeout(60000);
//Set headers
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("x-filename", fileName);
conn.setRequestProperty("x-filesize", fileSize);
conn.setRequestProperty("x-filehash", sha256);
//Write binary data
System.out.println("\nWriting data...");
OutputStream out = conn.getOutputStream();
out.write(bytesData);
out.flush();
//Check connection
//if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
// throw new RuntimeException("FAILED!!! HTTP error code: " +
// conn.getResponseCode() + " --- " +
// conn.getResponseMessage());
//}
//Get response
System.out.println("\nGetting response...");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//Print response
System.out.println("\nOutput from Server .... \n");
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
但我没有得到任何结果,只是:
Writing data...
Getting response...
Output from Server:
如果我取消注释下面的行,//Check connection
我会得到Exception
:
java.lang.RuntimeException: FAILED!!! HTTP error code: 503 --- OK
如果我更改Content-Type
标题,multipart/form-data
我会得到不同的Exception
:
java.lang.RuntimeException: FAILED!!! HTTP error code: 400 --- OK
我对 HTTP 连接等不太了解,也不知道发生了什么……
关于可能发生的事情有什么想法吗?
注意:我在同一个应用程序中使用 API 的其他 (GET) 方法,它们运行良好。