七牛云 java 上传文件空指针错误

新手上路,请多包涵

Exception in thread "main" java.lang.NullPointerException

at com.jany.controllertest.UploadTest.upload(UploadTest.java:61)
at com.jany.controllertest.UploadTest.main(UploadTest.java:44)

System.out.println(r.toString());

public void upload() throws IOException {

    try {
        //调用put方法上传
        Response res = uploadManager.put(FilePath, key, getUpToken());
        //打印返回的信息
        System.out.println(res.bodyString());
    } catch (QiniuException e) {
        Response r = e.response;
        // 请求失败时打印的异常的信息
        System.out.println(r.toString());//*这行空指针错误*
        try {
            //响应的文本信息
            System.out.println(r.bodyString());
        } catch (QiniuException e1) {
            //ignore
        }
    }
}


阅读 3.6k
1 个回答

你试试这个上传代码:

//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释

UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "your access key";
String secretKey = "your secret key";
String bucket = "your bucket name";
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
String localFilePath = "/home/qiniu/test.png";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;

Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);

try {
    Response response = uploadManager.put(localFilePath, key, upToken);
    //解析上传成功的结果
    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    System.out.println(putRet.key);
    System.out.println(putRet.hash);
} catch (QiniuException ex) {
    Response r = ex.response;
    System.err.println(r.toString());
    try {
        System.err.println(r.bodyString());
    } catch (QiniuException ex2) {
        //ignore
    }
}
logo
七牛云问答
子站问答
访问
宣传栏