I'm trying to handle a simple base64 string in my HTTP server by sending a POST request from postman with the String i need.
When I debug my server, i can see the request coming in, but the parameter is not transmitted.
I found this piece of code to handle POST request, but even though i see the request coming in, I cannot retrieve the value.
Any help would be appreciated, this is what I got now, and the response is empty:
public void handle(HttpExchange t) throws IOException, FileNotFoundException {
Map<String, Object> parameters = new HashMap<String, Object>();
InputStreamReader isr = new InputStreamReader(t.getRequestBody(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
parseQuery(query, parameters);
// send response
String response = "lol";
for (String key : parameters.keySet()) {
response += key + " = " + parameters.get(key) + "\n ";
}
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.toString().getBytes());
os.close();
public static void parseQuery(String query, Map<String, Object> parameters) throws UnsupportedEncodingException {
if (query != null) {
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0) {
key = URLDecoder.decode(param[0],
System.getProperty("file.encoding"));
}
if (param.length > 1) {
value = URLDecoder.decode(param[1],
System.getProperty("file.encoding"));
}
if (parameters.containsKey(key)) {
Object obj = parameters.get(key);
if (obj instanceof List<?>) {
List<String> values = (List<String>) obj;
values.add(value);
} else if (obj instanceof String) {
List<String> values = new ArrayList<String>();
values.add((String) obj);
values.add(value);
parameters.put(key, values);
}
} else {
parameters.put(key, value);
}
}
}
}
Related
I have been working on my own Http Client Class, and i want a way to implement the onload and oerror feature like, "declaring an event and actions for that event", if an error with the connection happened i must have the ability to specify a custom action for it.
public static void Error(int code){
System.out.println("Oops, something went wrong Error code:" + code.toString());
}
URL url = new URL("http://example.com/");
Map<String, String> params = new HashMap<String, String>();
params.put("key","value");
http_client client = new http_client(url, "GET", params , true);
client.onError = Error(client.ErrorCode);
Something like that.
Here is my class:
class http_client {
protected String responseText;
protected boolean loaded = false;
protected boolean error = false;
public http_client(URL url, String method , Map<String,String> parameters , boolean cache) throws IOException, ProtocolException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status > 299){
error = true;
}
connection.setRequestMethod(method);
if(method == "POST"){
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
connection.setUseCaches(cache);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream s = new DataOutputStream(connection.getOutputStream());
s.writeBytes(paramToStr(parameters));
s.flush();
s.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String CurrentLine;
int lines = 0;
while((CurrentLine = reader.readLine()) != null){
lines += 1;
response.append(CurrentLine + "\n");
}
reader.close();
responseText = response.toString();
responseText = responseText.substring(0 , responseText.length() - 1);
if(lines == 1){
responseText = responseText.replace("\n","");
}
loaded = true;
}
public static String paramToStr(Map<String, String> parameters) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
result.append("?");
for(Map.Entry<String,String> entry: parameters.entrySet()){
String key = URLEncoder.encode(entry.getKey() , "UTF-8");
String value = URLEncoder.encode(entry.getValue() , "UTF-8");
result.append(key);
result.append("=");
result.append(value);
result.append("&");
}
String str = result.toString();
str = result.substring(0 , str.length() - 1);
return str;
}
}
Thanks in advance.
You can use the Function Interface Java provides:
class http_client {
protected String responseText;
protected boolean loaded = false;
protected Function<Integer, Void> success;
protected Function<Integer, Void> error;
public http_client(URL url, String method , Map<String,String> parameters , boolean cache, Function<Integer, String>success, Function<Integer, String> error) throws IOException, ProtocolException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status > 299){
error.apply(status);
} else {
success.apply(status);
}
...
}
}
to call it just pass some lambda function
...
http_client client = new http_client(url, "GET", params , true, status -> System.out.println("success! " + status), status -> System.out.println("error " + status));
If I use Action=GetServiceStatus, the program below works fine, returning "200 OK" and an XML response as MWS scratchpad.
But if I just change Action="GetOrder" (and add the required extra string AmazonOrderId.Id.1=xxx-5684184-6801000) then it gives me error 403 "SignatureDoesNotMatch" <RequestID>b055a685-dfbb-494b-8cf5-bcec31e2fa3a</RequestID>.
The program, except for sending the request to read the URL, is taken from Amazon documentation. I copied the query string with the URL.
public class AmazonExample {
private static final String CHARACTER_ENCODING = "UTF-8";
final static String ALGORITHM = "HmacSHA256";
public static void main(String[] args) throws Exception {
String secretKey = "/ioTb2imZWZ/IHTKKfc62BFvBxxxxxxxxxxxxxxx";
// Use the endpoint for your marketplace
String serviceUrl = "https://mws.amazonservices.ca/";
// Create set of parameters needed and store in a map
HashMap<String, String> parameters = new HashMap<String,String>();
// Add required parameters. Change these as needed.
parameters.put("AWSAccessKeyId", urlEncode("AKIAJUTBJCxxxxxxxxxx"));
parameters.put("Action", urlEncode("GetServiceStatus")); //GetOrder
parameters.put("AmazonOrderId.Id.1", urlEncode("xxx-5684184-6801000"));
parameters.put("MWSAuthToken", urlEncode("amzn.mws.xxxxx7b8-5c81-3abc-06c2-c09e7dfd6ef3"));
parameters.put("SellerId", urlEncode("xxxxYI70TZB97A"));
parameters.put("SignatureMethod", urlEncode(ALGORITHM));
parameters.put("SignatureVersion", urlEncode("2"));
parameters.put("SubmittedFromDate",urlEncode("2015-03-14T17:02:05.264Z"));
parameters.put("Timestamp", urlEncode("2015-03-14T17:02:05.264Z"));
parameters.put("Version", urlEncode("2013-09-01"));
String formattedParameters = calculateStringToSignV2(parameters, serviceUrl);
String signature = sign(formattedParameters, secretKey);
// Add signature to the parameters and display final results
parameters.put("Signature", urlEncode(signature));
System.out.println(calculateStringToSignV2(parameters, serviceUrl));
try {
URL url = new URL("https://mws.amazonservices.ca/Orders/2013-09-01/?AWSAccessKeyId=xxxxxxxBJCIA4YSSWYNA&Action=GetServiceStatus&AmazonOrderId.Id.1=xxx-5684184-6801000&MWSAuthToken=amzn.mws.xxxxxxxx-5c81-3abc-06c2-c09e7dfd6ef3&SellerId=xxxxYI70TZB97A&Signature=yyO%2BrwMAtCcuEsYhG4KZILz2cyiSUcrAAWKqf3%2BZ454%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&SubmittedFromDate=2015-03-14T17%3A02%3A05.264Z&Timestamp=2015-03-14T17%3A02%3A05.264Z&Version=2013-09-01");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setConnectTimeout(50000);
BufferedReader br = null;
StringBuffer sbOrderResponse= new StringBuffer();
String order = ""; String str = "";
InputStream inputstream = null;
if(conn.getResponseCode() != 200 ) {
inputstream = conn.getErrorStream();
} else{
inputstream = conn.getInputStream();
}
br = new BufferedReader(new InputStreamReader((inputstream)));
StringBuffer buffer = new StringBuffer();
while ((order = br.readLine()) != null) {
sbOrderResponse.append(order);
str = str + order + "\n";
}
System.out.println(conn.getResponseCode() + " " + conn.getResponseMessage());
System.out.println(str);
} catch(Exception e)
{
System.out.println("Error " + e);
}
}
private static String calculateStringToSignV2(Map<String, String> parameters, String serviceUrl)
throws SignatureException, URISyntaxException {
// Sort the parameters alphabetically by storing
// in TreeMap structure
Map<String, String> sorted = new TreeMap<String, String>();
sorted.putAll(parameters);
// Set endpoint value
URI endpoint = new URI(serviceUrl.toLowerCase());
// Create flattened (String) representation
StringBuilder data = new StringBuilder();
data.append("GET\n");
data.append(endpoint.getHost());
data.append("\n/"); // /Orders/2013-09-01
data.append("\n");
Iterator<Entry<String, String>> pairs = sorted.entrySet().iterator();
while (pairs.hasNext()) {
Map.Entry<String, String> pair = pairs.next();
if (pair.getValue() != null) {
data.append( pair.getKey() + "=" + pair.getValue());
}
else {
data.append( pair.getKey() + "=");
}
// Delimit parameters with ampersand (&)
if (pairs.hasNext()) {
data.append( "&");
}
}
return data.toString();
}
/*
* Sign the text with the given secret key and convert to base64
*/
private static String sign(String data, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException,
IllegalStateException, UnsupportedEncodingException {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(secretKey.getBytes(CHARACTER_ENCODING), ALGORITHM));
byte[] signature = mac.doFinal(data.getBytes(CHARACTER_ENCODING));
String signatureBase64 = new String(Base64.encodeBase64(signature), CHARACTER_ENCODING);
return new String(signatureBase64);
}
private static String urlEncode(String rawValue) {
String value = (rawValue == null) ? "" : rawValue;
String encoded = null;
try {
encoded = URLEncoder.encode(value, CHARACTER_ENCODING)
.replace("+", "%20")
.replace("*", "%2A")
.replace("%7E","~");
} catch (UnsupportedEncodingException e) {
System.err.println("Unknown encoding: " + CHARACTER_ENCODING);
e.printStackTrace();
}
return encoded;
}}
First,
I've searched a lot to find a solution but were not able to find an appropriate one.
Environment
(productive) Mongoose WebServer replies to simple GET-requests (all data are transmitted via QueryString)
Apache HttpClient (single instance!) used to make hundreds of thousands single requests sequentially.
Apache HttpClient interacting with mongoose works quite well
// after each request
getMethod.releaseConnection();
...
Problem
(Mock) implementation of WebServer with Sun HttpServer works fine with FireFox / Curl
Using Apache HttpClient as with running against productive Server, performance is horrible (~ 1 request/second) on client
Using Apache HttpClient with following code found on the net results in
vast performance gain on client
resource waste due to as many open sockets in CLOSE_WAIT state as requests processed (until no more FDs ara available!)
Code:
HttpConnectionManager mgr = httpClient.getHttpConnectionManager();
if (mgr instanceof SimpleHttpConnectionManager) {
((SimpleHttpConnectionManager)mgr).shutdown();
}
Obviously I am mising something in the http server implementation, which causes this extreme "sloweness"
Any hint/help is appreciated.
Thanks in advance!
Code
HttpServer
public static void main(String[] args) throws Exception {
//System.setProperty("sun.net.httpserver.maxIdleConnections", "10");
//System.setProperty("sun.net.httpserver.idleInterval", "2000");
HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress("localhost", 11111), -1);
InetSocketAddress addr = server.getAddress();
HttpContext contextSearch = server.createContext("/search.to",
new TrufflesSearchHandler());
contextSearch.getFilters().add(new ParameterFilter());
server.setExecutor(null); // creates a default executor
server.start();
}
HttpHandler
static class SearchHandler implements HttpHandler {
private JSONParser jsonParser = new JSONParser();
public void handle(HttpExchange exchange) throws IOException {
Map<String, Object> params = (Map<String, Object>) exchange
.getAttribute("parameters");
String expectedResponse = "";
int expectedHitPlace = -1;
try {
expectedResponse = (String) params.get("expectedResponse");
expectedHitPlace = Integer.parseInt((String) params
.get("expectedHitPlace"));
} catch (Exception e) {
e.printStackTrace();
}
JSONArray resultArray = null;
try {
resultArray = (JSONArray) jsonParser.parse(new String(Base64
.decodeBase64(expectedResponse)));
fillResponseWithDummyData(resultArray, expectedHitPlace);
} catch (ParseException e) {
e.printStackTrace();
}
String response = "{ \"results\": " + resultArray + "}";
Headers headers = exchange.getResponseHeaders();
headers.add("Connection", "keep-alive");
headers.add("Content-Type", "text/plain");
headers.add("Content-length", "" + response.getBytes().length);
// headers.add("Keep-Alive", "timeout=5 max=10");
exchange.sendResponseHeaders(200, 0);
// exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.flush();
os.close();
// exchange.close();
}
ParameterFilter
#SuppressWarnings("restriction")
public class ParameterFilter extends Filter {
#Override
public String description() {
return "Parses the requested URI for parameters";
}
#Override
public void doFilter(HttpExchange exchange, Chain chain)
throws IOException {
parseGetParameters(exchange);
parsePostParameters(exchange);
chain.doFilter(exchange);
}
private void parseGetParameters(HttpExchange exchange)
throws UnsupportedEncodingException {
Map<String, Object> parameters = new HashMap<String, Object>();
URI requestedUri = exchange.getRequestURI();
String query = requestedUri.getRawQuery();
parseQuery(query, parameters);
exchange.setAttribute("parameters", parameters);
}
private void parsePostParameters(HttpExchange exchange)
throws IOException {
if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
#SuppressWarnings("unchecked")
Map<String, Object> parameters =
(Map<String, Object>)exchange.getAttribute("parameters");
InputStreamReader isr =
new InputStreamReader(exchange.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
parseQuery(query, parameters);
}
}
private void parseQuery(String query, Map<String, Object> parameters)
throws UnsupportedEncodingException {
String encoding = System.getProperty("file.encoding");
if (query != null) {
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0) {
key = URLDecoder.decode(param[0],
encoding);
}
if (param.length > 1) {
value = URLDecoder.decode(param[1],
encoding);
}
if (parameters.containsKey(key)) {
Object obj = parameters.get(key);
if(obj instanceof List<?>) {
List<String> values = (List<String>)obj;
values.add(value);
} else if(obj instanceof String) {
List<String> values = new ArrayList<String>();
values.add((String)obj);
values.add(value);
parameters.put(key, values);
}
} else {
parameters.put(key, value);
}
}
}
}
}
I am trying to build a simple HTTP client program that sends a request to a web server and prints the response out to the user.
I have got the following error when I run my code and I am not sure what is causing it:
-1
Exception in thread "main" java.lang.IllegalArgumentException: port out of range:-1
at java.net.InetSocketAddress.(InetSocketAddress.java:118)
at java.net.Socket.(Socket.java:189)
at com.example.bookstore.MyHttpClient.execute(MyHttpClient.java:18)
at com.example.bookstore.MyHttpClientApp.main(MyHttpClientApp.java:29)
Java Result: 1
Below is my MyHttpClient.java class
public class MyHttpClient {
MyHttpRequest request;
public MyHttpResponse execute(MyHttpRequest request) throws IOException {
this.request = request;
int port = request.getPort();
System.out.println(port);
//Create a socket
Socket s = new Socket(request.getHost(), request.getPort());
//Create I/O streams
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter outToServer = new PrintWriter(s.getOutputStream());
//Get method (POST OR GET) from request
String method = request.getMethod();
//Create response
MyHttpResponse response = new MyHttpResponse();
//GET Request
if(method.equalsIgnoreCase("GET")){
//Construct request line
String path = request.getPath();
String queryString = request.getQueryString();
//Send request line to server
outToServer.println("GET " + path + " HTTP/1.0");
//=================================================\\
//HTTP RESPONSE
//RESPONSE LINE
//Read response from server
String line = inFromServer.readLine();
//Get response code - should be 200.
int status = Integer.parseInt(line.substring(9, 3));
//Get text description of response code - if 200 should be OK.
String desc = line.substring(13);
//HEADER LINES
//Loop through headers until get to blank line...
//Header name: Header Value - structure
do{
line = inFromServer.readLine();
if(line != null && line.length() == 0){
//line is not blank
//header name start of line to the colon.
String name = line.substring(0, line.indexOf(": "));
//header value after the colon to end of line.
String value = String.valueOf(line.indexOf(": "));
response.addHeader(name, value);
}
}while(line != null && line.length() == 0);
//MESSAGE BODY
StringBuilder sb = new StringBuilder();
do{
line = inFromServer.readLine();
if(line != null){
sb.append((line)+"\n");
}
}while(line != null);
String body = sb.toString();
response.setBody(body);
//return response
return response;
}
//POST Request
else if(method.equalsIgnoreCase("POST")){
return response;
}
return response;
}
}
This is the MyHttpClientApp.java class
public class MyHttpClientApp {
public static void main(String[] args) {
String urlString = null;
URI uri;
MyHttpClient client;
MyHttpRequest request;
MyHttpResponse response;
try {
//==================================================================
// send GET request and print response
//==================================================================
urlString = "http://127.0.0.1/bookstore/viewBooks.php";
uri = new URI(urlString);
client = new MyHttpClient();
request = new MyHttpRequest(uri);
request.setMethod("GET");
response = client.execute(request);
System.out.println("=============================================");
System.out.println(request);
System.out.println("=============================================");
System.out.println(response);
System.out.println("=============================================");
}
catch (URISyntaxException e) {
String errorMessage = "Error parsing uri (" + urlString + "): " + e.getMessage();
System.out.println("MyHttpClientApp: " + errorMessage);
}
catch (IOException e) {
String errorMessage = "Error downloading book list: " + e.getMessage();
System.out.println("MyHttpClientApp: " + errorMessage);
}
}
}
MyHttpRequest
public class MyHttpRequest {
private URI uri;
private String method;
private Map<String, String> params;
public MyHttpRequest(URI uri) {
this.uri = uri;
this.method = null;
this.params = new HashMap<String, String>();
}
public String getHost() {
return this.uri.getHost();
}
public int getPort() {
return this.uri.getPort();
}
public String getPath() {
return this.uri.getPath();
}
public void addParameter(String name, String value) {
try {
name = URLEncoder.encode(name, "UTF-8");
value = URLEncoder.encode(value, "UTF-8");
this.params.put(name, value);
}
catch (UnsupportedEncodingException ex) {
System.out.println("URL encoding error: " + ex.getMessage());
}
}
public Map<String, String> getParameters() {
return this.params;
}
public String getQueryString() {
Map<String, String> parameters = this.getParameters();
// construct StringBuffer with name/value pairs
Set<String> names = parameters.keySet();
StringBuilder sbuf = new StringBuilder();
int i = 0;
for (String name : names) {
String value = parameters.get(name);
if (i != 0) {
sbuf.append("&");
}
sbuf.append(name);
sbuf.append("=");
sbuf.append(value);
i++;
}
return sbuf.toString();
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
#Override
public String toString() {
StringBuilder sbuf = new StringBuilder();
sbuf.append(this.getMethod());
sbuf.append(" ");
sbuf.append(this.getPath());
if (this.getMethod().equals("GET")) {
if (this.getQueryString().length() > 0) {
sbuf.append("?");
sbuf.append(this.getQueryString());
}
sbuf.append("\n");
sbuf.append("\n");
}
else if (this.getMethod().equals("POST")) {
sbuf.append("\n");
sbuf.append("\n");
sbuf.append(this.getQueryString());
sbuf.append("\n");
}
return sbuf.toString();
}
}
MyHttpResponse
public class MyHttpResponse {
private int status;
private String description;
private Map<String, String> headers;
private String body;
public MyHttpResponse() {
this.headers = new HashMap<String, String>();
}
public int getStatus() {
return this.status;
}
public void setStatus(int status) {
this.status = status;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, String> getHeaders() {
return this.headers;
}
public void addHeader(String header, String value) {
headers.put(header, value);
}
public String getBody() {
return body;
}
public void setBody(String is) {
this.body = is;
}
#Override
public String toString() {
StringBuilder sbuf = new StringBuilder();
sbuf.append("Http Response status line: ");
sbuf.append("\n");
sbuf.append(this.getStatus());
sbuf.append(" ");
sbuf.append(this.getDescription());
sbuf.append("\n");
sbuf.append("---------------------------------------------");
sbuf.append("\n");
sbuf.append("Http Response headers: ");
sbuf.append("\n");
for (String key: this.getHeaders().keySet()) {
String value = this.getHeaders().get(key);
sbuf.append(key);
sbuf.append(": ");
sbuf.append(value);
sbuf.append("\n");
}
sbuf.append("---------------------------------------------");
sbuf.append("\n");
sbuf.append("Http Response body: ");
sbuf.append("\n");
sbuf.append(this.getBody());
sbuf.append("\n");
return sbuf.toString();
}
}
Any ideas what might be happening? Many thanks in advance.
I guess your request don't specify a port explicitly and so your request.getPort() is returning -1. And then you try to connect to port -1. And this is illegal.
Instead of that, before using the port : check if it is <= 0 and in this case use 80 as default value.
int port = request.getPort();
if(port<=0) port=80;
since there is no set port in the URI, as of javadocs -1 is returned from port:
http://docs.oracle.com/javase/6/docs/api/java/net/URI.html#getPort()
The port component of this URI, or -1 if the port is undefined
Lots of recreating the wheel going on here. Why not use Java's in-built HTTP client (at least; there are also many third-party HTTP clients out there that do very nicely).
URL url = new URL("http://stackoverflow.com");
final HttpURLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.connect();
int responseCode = connection.getResponseCode();
etc.
use
uri = URIUtil.encodeQuery(urlString)
instead
uri = new URI(urlString);
I can't figure this one out. I'm trying to dynamically roll keys. I can create the POST request fine, but receive a 400 error and a stacktrace with an IOException when I call post. Below is a self-contained example. I'm using JSCH to generate keys. API doc: http://developer.github.com/v3/users/keys/
The API call: POST /user/keys
public static class LiberalHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static String post(String requestUrl, Map<String, String> params,
String username, String password) throws Exception {
String data = "";
int paramCount = 1;
for (Entry<String, String> param : params.entrySet()) {
if (paramCount == 1) {
data = URLEncoder.encode(param.getKey(), "UTF-8") + "="
+ URLEncoder.encode(param.getValue(), "UTF-8");
} else {
data += "&" + URLEncoder.encode(param.getKey(), "UTF-8") + "="
+ URLEncoder.encode(param.getValue(), "UTF-8");
}
paramCount++;
}
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) (url).openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setHostnameVerifier(new LiberalHostnameVerifier());
BASE64Encoder enc = new BASE64Encoder();
String userAuth = username + ":" + password;
String encodedAuthorization = enc.encode(userAuth.getBytes());
conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
String response = "";
while ((line = rd.readLine()) != null) {
response += line;
}
wr.close();
rd.close();
return response;
}
public static KeyPair generateKey(String filename) throws Exception {
JSch jsch = new JSch();
try {
KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
kpair.setPassphrase("");
kpair.writePrivateKey(filename + ".pem");
kpair.writePublicKey(filename + ".pub", "Auto-generated.");
System.out.println("Finger print: " + kpair.getFingerPrint());
// kpair.dispose();
return kpair;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getFileContents(File file) throws Exception {
byte[] buffer = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
f.read(buffer);
return new String(buffer);
}
public static String createKey(String title) throws Exception {
generateKey(title);
final String key = getFileContents(new File(
"/Users/franklovecchio/Desktop/development/" + title
+ ".pub"));
System.out.println("key: " + key);
Map<String, String> params = new HashMap<String, String>() {
{
put("title", title);
put("key", key);
}
};
return post("https://api.github.com/user/keys", params, "username",
"password");
}
// call createKey("key);
Thanks to #nico_ekito and #J-16 SDiZ for helping in the right direction. If you look closely at the documentation, the request doesn't use standard POST parameters, but rather takes JSON as Raw Input, and the ssh-rsa key can NOT be encoded. Next up, I can't get GSON to not encode a string, even using disableHtmlEscaping. So, I had to fake it:
String json = "{\"title\":\"" + title + "\",\"key\":\"" + key.trim() + "\"}";
Did you try a ssh library (e.g. JSch). They can generate RSA key in SSH consumable format.