用java代码上传文件到github
时间: 2024-05-02 16:11:43 浏览: 169
上传文件的java代码
要使用Java代码上传文件到GitHub,可以使用GitHub API。以下是一个示例代码:
```java
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class GitHubUploader {
private static final String API_URL = "https://api.github.com/repos/{owner}/{repo}/contents/{path}";
private final String owner;
private final String repo;
private final String token;
public GitHubUploader(String owner, String repo, String token) {
this.owner = owner;
this.repo = repo;
this.token = token;
}
public void uploadFile(String path, File file) throws IOException {
String content = Base64.encodeBase64String(readFile(file));
String apiUrl = API_URL
.replace("{owner}", owner)
.replace("{repo}", repo)
.replace("{path}", path);
CloseableHttpClient client = HttpClients.createDefault();
HttpPut request = new HttpPut(apiUrl);
addHeaders(request);
addRequestBody(request, content);
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
System.out.println("File uploaded successfully");
} else {
System.err.println("Failed to upload file: " + response.getStatusLine());
}
EntityUtils.consume(response.getEntity());
response.close();
client.close();
}
private void addHeaders(HttpRequestBase request) {
request.setHeader(HttpHeaders.ACCEPT, "application/vnd.github+json");
request.setHeader(HttpHeaders.AUTHORIZATION, "token " + token);
request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
}
private void addRequestBody(HttpPut request, String content) {
String body = String.format("{\"message\":\"Upload %s\",\"content\":\"%s\"}", request.getURI().getPath(), content);
request.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
}
private byte[] readFile(File file) throws IOException {
try (FileInputStream inputStream = new FileInputStream(file)) {
byte[] buffer = new byte[(int) file.length()];
inputStream.read(buffer);
return buffer;
}
}
}
```
在使用时,你需要替换以下三个参数:
- `owner`:你的GitHub用户名或组织名;
- `repo`:你要上传文件的仓库名称;
- `token`:一个GitHub Personal Access Token,用于进行API授权。
然后可以调用 `uploadFile` 方法上传文件。例如:
```java
GitHubUploader uploader = new GitHubUploader("username", "repo-name", "personal-access-token");
File file = new File("/path/to/file.txt");
uploader.uploadFile("path/to/file.txt", file);
```
这将会在 `repo-name` 仓库的 `path/to/file.txt` 路径下上传 `file.txt` 文件。
阅读全文