我正在测试通过 API 的 Java 客户端将文件上传到 CKAN/datahub.io 上的数据集。
public String uploadFile()
throws CKANException {
String returned_json = this._connection.MultiPartPost("", "");
System.out.println("r: " + returned_json);
return returned_json;
}
和
protected String MultiPartPost(String path, String data)
throws CKANException {
URL url = null;
try {
url = new URL(this.m_host + ":" + this.m_port + path);
} catch (MalformedURLException mue) {
System.err.println(mue);
return null;
}
String body = "";
HttpClient httpclient = new DefaultHttpClient();
try {
String fileName = "D:\\test.jpg";
FileBody bin = new FileBody(new File(fileName),"image/jpeg");
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
HttpPost postRequest = new HttpPost("http://datahub.io/api/storage/auth/form/2013-01-24T130158/test.jpg");
postRequest.setEntity(reqEntity);
postRequest.setHeader("X-CKAN-API-Key", this._apikey);
HttpResponse response = httpclient.execute(postRequest);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("status code: " + statusCode);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String line;
while ((line = br.readLine()) != null) {
body += line;
}
System.out.println("body: " + body);
} catch (IOException ioe) {
System.out.println(ioe);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}
我收到 POST 请求的 2 个响应:
当我尝试上传的 jpeg 为 2.83 Mb 时出现 413 错误(“请求实体太大”)。当我将文件缩小到更小的尺寸时,这会消失。文件大小上传有限制吗?
500 错误(“内部服务器错误”)。这就是我卡住的地方。这可能与我在 datahub.io 上的数据集未“启用数据存储”这一事实有关?(我在数据集中的资源文件旁边看到一个禁用的“数据 API”按钮,工具提示说:“由于数据存储已禁用,此资源的数据 API 不可用”
=> 是这个 500 错误的可能原因吗?如果是这样,我如何从客户端启用它?(指向 Python 代码的指针会很有用!)
谢谢!
PS:我用于测试目的的数据集:http: //datahub.io/dataset/testapi