It is a continuation of Call Rest API of GitHub from Java Socket API Let's call the GitHub API that commits the file to the repository for GitHub from Java's Soceket API
In order to make changes to the GitHub repository, you need to consider authentication when calling the GitHub API. This time we will authenticate with OAuth2 authentication, so we will issue a Personal access token on GitHub in advance (Detailed information on how to issue a Personal Access Token can be found on the reference site below.)
The following processing has been added from Last implementation.
--Added logic to generate json to generate necessary parameters on GitHub --Added logic to convert files to commit to GitHub to Base64 format
--If no authentication token is set, a 404 error will be returned --If you specify something other than PUT for the send method, a 404 error will be returned. --A 422 error is returned if the json parameter sent to GitHub is incorrect --Specify that the destination path must include files Specifying a directory returns a 422 error
-I tried to summarize various things about Github API There is a description about basic authentication related to GitHub API. This is a site you should read when implementing the GitHub API.
Test.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
//Add files to your GitHub repository using GitHub's REST API v3
//The format of REST API v3 is
// /repos/:owner/:repo/contents/:path
//Becomes
private static final String ACCESS_KEY ="*********";
private static final String GITHUB_RESTAPI_PATH = "https://api.github.com/repos/triple4649/images/contents/img/mypicture.png?access_token=%s";
public static void main(String[] args) throws Exception {
HttpsURLConnection con = createHttpsURLConnection(String.format(GITHUB_RESTAPI_PATH, ACCESS_KEY)
,"PUT");
//Commit the image file to GitHub with Rest API
putContents(con,createJson());
//Output header information of Rest API response
printHeaderFields(con);
//Output the result of Rest API response
printBody(con);
con.disconnect();
}
//Write JSON to Stream
private static void putContents(HttpsURLConnection con,byte[] b) throws Exception{
con.setDoOutput(true);
OutputStream o = con.getOutputStream();
o.write(b);
o.flush();
}
//Converts a file with the specified path to Base64 format
public static String converToBase64(String path)throws Exception{
return Base64.getEncoder()
.encodeToString(
Files.readAllBytes(Paths.get(path)));
}
//Generate HttpsURLConnection by specifying HTTP send method
private static HttpsURLConnection createHttpsURLConnection (String path,String method) throws Exception{
HttpsURLConnection con = createHttpsURLConnection (path);
con.setRequestMethod(method);
return con;
}
//Generate data to commit to GitHub
private static byte[] createJson() throws Exception{
Map <String,Object> map = new LinkedHashMap<String,Object>();
Map <String,String> nestmap=new LinkedHashMap<String,String>();
nestmap.put("name", "triple");
nestmap.put("email", "[email protected]");
map.put("committer",nestmap);
map.put("message","GitHub API");
map.put("content",converToBase64("./CA390046.JPG"));
return new ObjectMapper()
.writeValueAsBytes(map);
}
//Generate a URLConnection for a TLS connection(Unverified version of certification)
//Request method is the default(Get)
private static HttpsURLConnection createHttpsURLConnection (String path) throws Exception{
SSLSocketFactory factory = null;
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new NonAuthentication[] { new NonAuthentication() },
null);
factory = ctx.getSocketFactory();
URL url = new URL(path);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(factory);
return con;
}
//Output header information
private static void printHeaderFields(HttpsURLConnection con){
con.getHeaderFields()
.entrySet()
.stream()
.map(e->String.format("key:%s value:%s", e.getKey(),e.getValue()))
.forEach(System.out::println);
}
//Output Body information
private static void printBody(HttpsURLConnection con) throws Exception{
new BufferedReader(new InputStreamReader(
con.getInputStream()))
.lines()
.forEach(System.out::println);
}
}
class NonAuthentication implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
Recommended Posts