【发布时间】:2013-05-10 17:57:08
【问题描述】:
此问题与one I posted yesterday 有关,但我发现了更多信息,现在遇到了另一个错误。我从 Android 中删除了代码,直接从 Java 中尝试。我还尝试了 2 种不同的方式来获取多帖子信息。 userContext 具有写权限,因为我可以轻松创建模块。
我尝试过的一种方法:
String json = "{\"IsHidden\": false, \"IsLocked\": false, \"ShortTitle\": "Test\", \"Type\": 1, \r\n" + "\"DueDate\": null, \"Url\": \"file.txt\", \r\n" + "\"StartDate\": null, \"TopicType\": 1, \"EndDate\": null, \"Title\": \"Test topic \r\n" + "content\"} \r\n";
URI uri = userContext.createAuthenticatedUri("/d2l/api/le/1.0/Orgid/content/modules/moduleid/structure/", "POST");
MultipartEntity entity = new MultipartEntity();
StringBody part1 = new StringBody(json, "application/json", null);
entity.addPart("json", part1);
File file = new File("test.txt");
FileBody part2 = new FileBody(file, "test.txt", "text/plain", null);
entity.addPart("file", part2);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
System.out.println("Statusline: " + response.getStatusLine());
这是我尝试的另一种方式:
String body = "--xxBOUNDARYxx \r\n" +
"Content-Type: application/json \r\n" +
"{\"IsHidden\": false, \"IsLocked\": false, \"ShortTitle\": \"Test\", \"Type\": 1, \r\n" +
"\"DueDate\": null, \"Url\": \"file.txt\", \r\n" +
"\"StartDate\": null, \"TopicType\": 1, \"EndDate\": null, \"Title\": \"Test topic \r\n" +
"content\"} \r\n" +
"--xxBOUNDARYxx \r\n" +
"Content-Disposition: form-data; name=\"\"; filename=\"file.txt\" \r\n" +
"Content-Type: text/plain \r\n" +
" This is a sample text file \r\n" +
"with some text content. \r\n" +
"--xxBOUNDARYxx--";
URI uri = userContext.createAuthenticatedUri("/d2l/api/le/1.0/orgid/content/modules/moduleid/structure/", "POST");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
post.addHeader("Content-Type", "multipart/mixed;boundary=xxBOUNDARYxx");
post.setEntity(new StringEntity(body));
HttpResponse response = httpClient.execute(post);
System.out.println("Statusline: " + response.getStatusLine());
这两种方法都给出了相同的结果:
Statusline: HTTP/1.1 302 Found
Response: <html><head><title>Object moved</title></head><body><h2>Object moved to <a href="/d2l/error/404">here</a>.</h2></body></html>
恕我直言,这两种技术都应该按照here 的描述创建结构,所以我真的被卡住了。我还尝试将完整的 /content/enforced/.../file.txt 用于 Url,结果相同。
【问题讨论】:
-
我注意到在第一个 sn-p 中我在一个地方使用了
file.txt,在另一个地方使用了test.txt。我固定使用相同的名称,但仍然得到相同的结果。
标签: http rest multipart desire2learn valence