I need to figure out a way to check if minecraft username and password is valid.
I have found this documentation which is telling a lot of things about the minecraft authentication : http://wiki.vg/Authentication
Looks like it needs a JSON HTTP POST Request but I have no idea how to do that :S
I have searched a lot and went through a lot of exemple but none of these works. The best result I had is no result printed in console or a 403 error.
Thanks
I figured out how to do it !
private static String MakeJSONRequest(String username, String password){
JSONObject json1 = new JSONObject();
json1.put("name", "Minecraft");
json1.put("version", 1);
JSONObject json = new JSONObject();
json.put("agent", json1);
json.put("username", username);
json.put("password", password);
return json.toJSONString();
}
private static String httpRequest(URL url, String content) throws Exception {
byte[] contentBytes = content.getBytes("UTF-8");
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(contentBytes.length));
OutputStream requestStream = connection.getOutputStream();
requestStream.write(contentBytes, 0, contentBytes.length);
requestStream.close();
String response = "";
BufferedReader responseStream;
if (((HttpURLConnection) connection).getResponseCode() == 200) {
responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
} else {
responseStream = new BufferedReader(new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8"));
}
response = responseStream.readLine();
responseStream.close();
if (((HttpURLConnection) connection).getResponseCode() != 200) {
//Failed to login (Invalid Credentials or whatever)
}
return response;
}
How to use it :
System.out.println(httpRequest(new URL("https://authserver.mojang.com/authenticate"), MakeJSONRequest("YourUsername", "YourPassword")));
Related
I have spring boot application in which I get the streamName as a parameter, but now I don't want it to work in postman, but in another program in which the streamName is String that is created when calling a function. Previously I was giving it as json, but now I want to give it as parameter and I have no idea how can I do it.
This is my Request in Spring boot:
#PostMapping
#ResponseBody
public String addStream(#RequestParam("streamName") String streamName) {
String key = getRandomHexString();
streamService.addStream(new Stream(streamName,key));
return key;
}
and this is in another program where i want to make this method:
public void onHTTPPostRequest(String streamName) throws IOException {
PostResponse postResponse = new PostResponse();
postResponse.setStreamName(streamName);
Gson gson = new Gson();
String jsonString = gson.toJson(postResponse);
getLogger().info("POST Body " + jsonString);
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=");
HttpURLConnection conn = (HttpURLConnection) pipedreamURL.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonString.getBytes("UTF-8"));
os.close();
int responseCode = conn.getResponseCode();
getLogger().info(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
simply add it to the URL string:
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=" + streamName);
I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.
Sorry to ask you this but I am kinda new in Java.
I have the following classes:
protected class LoginMethod{
public LoginMethod() throws MalformedURLException, UnsupportedEncodingException, IOException{
URL url = new URL("http://example.com/login");
Map<String,Object> params = new LinkedHashMap<>();
params.put("username", user);
params.put("password", password );
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
try{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
token += String.valueOf((char)c);
System.out.println(token);
new LoggedIn();
}catch(IOException es){
System.out.println(es);
}
}
}
And this returns a JSON String with some token.
And the next class :
protected class DoStuff{
public DoStuff() throws MalformedURLException, UnsupportedEncodingException, IOException, ParseException{
JSONParser parser = new JSONParser();
URL url = new URL("http://example.com/DoStuff");
Map<String,Object> params = new LinkedHashMap<>();
params.put("Do", "Stuff");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
try{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
stuff +=(char)c;
System.out.println(stuff);
new LogOut();
}catch(IOException er){
System.out.println(er);
}
}
}
This should return the DoStuff thing. But because I don't know how to keep session between those classes I get 401 error.
My question is how to keep the session between those classes or a tip how to put them into a single class that supports session keeping in mind they are called by separate buttons.
Thank you!
If the mentioned "http://example.com" is a webservice, the token which you received in the response is having session information. All you need to be do is to send the token back by setting in request header while calling dostuff method.
login response :
{ "token":"ewryoiuasdjhie8417098412","expires":"jun 10 2015"}
while calling dostuff
conn.setRequestProperty("token", "ewryoiuasdjhie8417098412");
The proper answer is the following:
In the second class we need to json decode the token received and add
conn.setRequestProperty("Authorization", token);
This works. Thanks StackOverflow for everything.
I have my bearerToken and userID as per Twitter instructions https://dev.twitter.com/docs/auth/application-only-auth and I want t get a list of followers.
I'm getting error 86, which isn't on the list of error codes https://dev.twitter.com/docs/error-codes-responses
Any pointers would be appreciated.
public String getTwitterFriends(String userID, String bearerToken) {
// Use App Bearer token to get public friends
String answer = "";
String param = "count=5000&cursor=-1&user_id=" + userID;
HttpURLConnection connection = null;
try {
// String request =
// "https://api.twitter.com:443/1.1/friends/ids.json?" + param;
String request = "https://api.twitter.com/1.1/friends/ids.json?"
+ param;
URL url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", false ? "true" : "false");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
// connection.setRequestProperty("Host", "api.twitter.com" +
// ":443");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Authorization", "Bearer "
+ bearerToken);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("User-Agent", "UnhappyChappy");
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestProperty("Content-Length", "" +
// Integer.toString(param.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
// wr.writeBytes(param);
wr.flush();
wr.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
StringBuilder str = new StringBuilder();
while ((line = reader.readLine()) != null) {
System.out.println(line);
str.append(line);
}
reader.close();
connection.disconnect();
answer = str.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(answer);
return answer;
}
It was the way I issued the GET. I had to go to a lower level on App Engine and use FetchOptions This worked for me, hopefully it will help someone else.
URL url = new URL(request);
HTTPRequest req = new HTTPRequest(url, HTTPMethod.GET);
req.addHeader(new HTTPHeader("Authorization", "Bearer " + bearerToken));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(req);
System.out.println(new String(response.getContent()));
I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....