java连接ipfs
1、使用Maven方式引入包:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependency>
<groupId>com.github.ipfs</groupId>
<artifactId>java-ipfs-api</artifactId>
<version>1.3.3</version>
</dependency>
2、代码demo:
package com.chainmaker.nft.service;
import io.ipfs.api.IPFS;
import io.ipfs.api.MerkleNode;
import io.ipfs.api.NamedStreamable;
import io.ipfs.multihash.Multihash;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@Service
@Slf4j
public class ipfsService {
private IPFS ipfs;
public void IPFSOpe(String ip) {
this.ipfs = new IPFS(ip);
}
public void upload(String upaddr) throws IOException {
//保存上传文件
NamedStreamable.FileWrapper savefile = new NamedStreamable.FileWrapper(new File(upaddr));
MerkleNode result = ipfs.add(savefile).get(0);
System.out.println(result.toString());
}
public void cat(String hash) throws IOException {
//参数为文件 hash
Multihash filePointer = Multihash.fromBase58(hash);
byte[] fileContents = ipfs.cat(filePointer);
System.out.println(new String(fileContents));
}
public void download(String hash, String downaddr) throws IOException {
//参数为文件 hash
Multihash filePointer = Multihash.fromBase58(hash);
byte[] fileContents = ipfs.cat(filePointer);
File downloadfile = new File(downaddr);
if(!downloadfile.exists()) {
downloadfile.createNewFile();
}
FileOutputStream fop = new FileOutputStream(downloadfile);
fop.write(fileContents);
fop.flush();
fop.close();
}
public static void main(String[] args) throws IOException {
String ip = "/ip4/127.0.0.1/tcp/5001";
String upaddr = "/root/lyzdfintech.com/image/test.log";
// String downaddr = "/root/lyzdfintech.com/image/test1.log";
// String hash = "QmNkspXsCVxsjVBG3FCoBJVfcD5zT15K3Uzo9J14NnLQru"; //test.txt
//String hash = "QmNkspXsCVxsjVBG3FCoBJVfcD5zT15K3Uzo9J14NnLQru"; //java.txt
ipfsService test = new ipfsService();
test.IPFSOpe(ip);
test.upload(upaddr);
//test.cat(hash);
// test.download(hash, downaddr);
}
}
异常汇总
1、java-sdk连接失败
java.lang.RuntimeException: Server returned status: 404 with body: and Trailer header: null
解决方案:
将8080 Gateway 改为API 5001
IPFS ipfs = new IPFS(“/ip4/127.0.0.1/tcp/8080”);
修改为
IPFS ipfs = new IPFS(“/ip4/127.0.0.1/tcp/5001”);