我需要从 Google App Engine 中运行的 Java 网络应用向 MediaFire REST API 发送 HTTP POST 请求 ,以便上传文件。
请参见上传功能文档here (几行)。
查看文档和一些研究,我编写了以下 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
下的行,我会得到一个异常
:
java.lang.RuntimeException: FAILED!!! HTTP error code: 503 --- OK
如果我更改 multipart/form-data
的 Content-Type
header ,我会得到不同的 Exception
:
java.lang.RuntimeException: FAILED!!! HTTP error code: 400 --- OK
我对 HTTP 连接等了解不多,也不知道发生了什么......
对可能发生的事情有什么想法吗?
<小时/>注意:我正在使用同一应用中 API 的其他 (GET) 方法,并且它们工作正常。
最佳答案
HTTP错误代码:400是错误请求的状态代码,这可能意味着服务器不排除multipart/form-data,503代码意味着服务器过载,因此该服务可能托管在不同的服务器/线程上在服务器上转移到其他 GET 方法,这可能会接收更多流量。
关于Java:发送 POST HTTP 请求以将文件上传到 MediaFire REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389585/