i am new to json parsing and i'm trying to figure out why it's returning null.
Here is my java code (if you aren't familiar with the spigot api https://hub.spigotmc.org/javadocs/spigot/overview-summary.html)
Can you tell me what i am doing wrong? i'll give the gson part of the code and then i'll give the rest. think of it as just outputting the json in a console if you don't feel like reading the api.
try {
URL hypixel = new URL("https://api.hypixel.net/player?key=apikey&name=" + username);
URLConnection urlConn = hypixel.openConnection();
urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
urlConn.getDoOutput();
try(final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
final JsonParser parser = new JsonParser();
parser.parse(reader.readLine());
final JsonObject object = parser.parse("").getAsJsonObject();
String userId = object.getAsJsonObject("player").get("_id").getAsString();
p.sendMessage(ChatColor.GREEN + "UID: " + userId);
}
} catch (IOException e) {
p.sendMessage(ChatColor.RED + "Something went wrong!");
}
(p.sendmessage would be the thing going in console)
Here is all of the code:
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player p = (Player) sender;
if(command.getName().equalsIgnoreCase("hypixel")) {
if(args.length == 2) {
String username = args[0];
try {
URL hypixel = new URL("https://api.hypixel.net/player?key=apikey&name=" + username);
URLConnection urlConn = hypixel.openConnection();
urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
urlConn.getDoOutput();
try(final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
final JsonParser parser = new JsonParser();
parser.parse(reader.readLine());
final JsonObject object = parser.parse("").getAsJsonObject();
String userId = object.getAsJsonObject("player").get("_id").getAsString();
p.sendMessage(ChatColor.GREEN + "UID: " + userId);
}
} catch (IOException e) {
p.sendMessage(ChatColor.RED + "Something went wrong!");
}
}
}
return false;
}
Any help is appreciated thank you!
(Oh and here is the part of the response from the api that i want to parse)
{"success":true,"player":{"_id":"5442f08f48b8f1e1e64a0400"}}
parser.parse("").getAsJsonObject()
is expecting "" to be JSON, which it is not.
Related
I have been trying to create a simple java web server everything works fine for files such as html or css but I'm unable to send image responses correctly. The problem is obviously with the image data that I'm sending but I'm not sure how to do it properly. I have been searching for any information about it for a long time not and I just can't find anything useful that would fix my problem.
Part of my code:
public void Send(String path) throws IOException {
File file = new File(path);
if(file.exists()) {
if(!file.isDirectory()) {
if(isImage(file)) {
InputStream is = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(is);
String response = "HTTP/1.1 200 OK" + CRLF + "Content-Length: " + bytes.length + CRLF;
response += "content-type: image/jpeg" + CRLF + CRLF;
outputStream.write(response.getBytes());
outputStream.write(bytes);
outputStream.write((CRLF + CRLF).getBytes());
outputStream.flush();
} else {
String data = "";
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
data += st;
}
int length = data.getBytes().length;
String response = "HTTP/1.1 200 OK" + CRLF + "Content-Length: " + length + CRLF;
response += CRLF + data + CRLF + CRLF;
br.close();
outputStream.write(response.getBytes());
}
return;
}
}
SendError("404 Not Found");
}
outputStream is OutputStream from a Socket.
I saw this but I think I'm only using streams at least for the image part.
I'm new to this so any help would be appreciated!
EDIT (more inforamtion):
Browser information:
Headers
Preview
The isImage(file) methode works fine I have tested it but here it is:
private boolean isImage(File file) {
String mimetype = new MimetypesFileTypeMap().getContentType(file);
String type = mimetype.split("/")[0];
return type.equals("image");
}
And the image is 2.jpg
EDIT 2
I wrote this code to write the content of the array in a text file:
String out = "";
for(int i = 0; i < bytes.length; i++) {
if(i%16 == 0) {
out += "\n";
}
out += String.format("%02X ", bytes[i]);
}
BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"));
writer.write(out);
writer.close();
So I checked the start of both the image and the array and they seem to be identical.
Start of the image data
Start if the array
After that I tried to create a client for testing:
private static void Get2(String link) throws IOException {
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.68");
con.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
con.setRequestProperty("Sec-Fetch-Site", "same-origin");
con.setRequestProperty("Sec-Fetch-Mode", "no-cors");
con.setRequestProperty("Sec-Fetch-Dest", "image");
con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
con.setRequestProperty("Accept-Language", "sl,en;q=0.9,en-GB;q=0.8,en-US;q=0.7");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setInstanceFollowRedirects(false);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
int i = 0;
while ((inputLine = in.readLine()) != null) {
if(i < 5) {
System.out.println(inputLine);
} else {
content.append(inputLine);
}
i++;
}
in.close();
con.disconnect();
BufferedWriter writer = new BufferedWriter(new FileWriter("test2.txt"));
writer.write(content.toString());
writer.close();
}
I called the function: Get2("http://localhost:8080/images/2.jpg");
And got saved data in the test2.txt. Inside I saw some parts of similar data but it's clearly something wrong with it. I'm not sure if I'm using this client test wrong so if I'm doing something wrong or should be using something else let me know.
Image (left test2.txt, right test.txt)
Thanks to everyone that will and already helped or had any suggestions.
I finally figured it out. Actually my bad for not providing everything.
String CRLF = "\n\r";
But apparently, it should only be \n.
I read somewhere that windows automatically adds \r after \n. I don't know if that's true but removing \r fixed my problem as before I had 2 empty lines right after GET / HTTP/1.1 so the other content was considered as part of the data.
As soon as I changed that everything worked fine.
Again thanks for your help!
EDIT
Nevermind. What I did wrong was the order of \n and \r. It should be \r\n not \n\r
I need to write a small tool in JAVA which will translate text from English to French using the Google translate API. Everything works but I have an apostrophe decoding problem.
Original text:
Inherit Tax Rate
Text translated with Google translate API:
Taux d' imposition hérité
How it should be:
Taux d'imposition hérité
This is my translate method(sorry for the long method):
private String translate(String text, String from, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2?key=" + sKey + "&q=" + encodedText + "&target=" + to + "&source=" + from;
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream googleStream;
if (conn.getResponseCode() == 200) {
googleStream = conn.getInputStream(); //success
} else
googleStream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(googleStream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String translatedText = obj.get("data").getAsJsonObject().
get("translations").getAsJsonArray().
get(0).getAsJsonObject().
get("translatedText").getAsString();
return translatedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException | JsonSyntaxException ex) {
System.err.println(ex.getMessage());
}
return null;
}
I'm using an XML writer to write the text and first I though that this has a problem, but I observed that the text is returned like this in the stream so I introduced the encoding parameter when I initialise the InputStreamReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(googleStream, "UTF-8"));
But I receive the string with the same problem. Any ideas about what I can do?
I think this problem is solved by using the format parameter (docs). It defaults to html, but you can change it to text to receive unencoded data. Your request should look like this:
String urlStr = "https://www.googleapis.com/language/translate/v2?key=" + sKey + "&q=" + encodedText + "&target=" + to + "&source=" + from + "&format=text";
Hi i'm trying to send course list which has more than 2,000 course info to mysqli through php file. but ! whenever i try to send list, it doesn't send it to server.
so can you help me to solve this problem..? :(
First, java source
public static void sendCourseInfoToDB(List<Subject> subjects, String url) {
try {
// url is my *.php file
URL target = new URL(url);
HttpURLConnection con = (HttpURLConnection) target.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "text/html; charset = utf-8");
DataOutputStream out = new DataOutputStream(con.getOutputStream());
int len = subjects.size();
for (int i = 0; i < len; ++i) {
//String t = subjects.get(i).toString();
out.writeBytes(subjects.get(i).toString());
out.flush();
}
out.flush();
out.close();
int responseCode = con.getResponseCode();
System.out.println("Post rqeust to Url : " + url);
System.out.println("Post Params : " + subjects.get(0).toString());
System.out.println("Resoponse Code : " + Integer.toString(responseCode));
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
Subject class overrides toString. return-statement used parameter is encoded UTF-8
like this :
courseCode = 12156&courseName = %EC%8B%A0%EC%86%8C%EC%9E%AC%EA%B3%B5%ED%95%99%EB%B6%80&subjectName = %EC%A2%85%ED%95%A9%EA%B3%BC%EC%A0%9C%EC%84%A4%EA%B3%841&kindOfSubject = %EC%A0%84%EA%B3%B5&score = 2
and php file
<?php
header("Content-Type : text/html; charset = utf-8");
$mysqli = new mysqli("localhost", "user", "password", "db");
if($mysqli->mysqli_errno) {
print $mysqli_error;
exit();
}
$courseCode = $_POST["courseCode"];
$courseName = $_POST["courseName"];
$subjectName = $_POST["subjectName"];
$kindOfSubject = $_POST["kindOfSubject"];
$score = $_POST["score"];
$mysqli->query("INSERT INTO COURSE VALUES('$courseCode', '$courseName', '$subjectName', '$kindOfSubject', '$score')");
$response = $courseCode;
echo $response;
?>
should i call 'sendCourseInfoToDB function every time when i send course info to DB ? i dont know what is wrong.. help me crazy coding people~!~
I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...
I'm using html cleaner to get data from a website...but I keep getting this error.
Server returned HTTP response code: 403 for URL: http://www.groupon.com/browse/chicago?z=skip
I'm not sure what I do wrong because I've use the same code before and its work perfectly.
is anyone able to help me please?.
Code is below:
public ArrayList ParseGrouponDeals(ArrayList arrayList) {
try {
CleanerProperties props = new CleanerProperties();
props.setTranslateSpecialEntities(true);
props.setTransResCharsToNCR(true);
props.setOmitComments(true);
TagNode root = new HtmlCleaner(props).clean(new URL("http://www.groupon.com/browse/chicago?z=skip"));
//Get the Wrapper.
Object[] objects = root.evaluateXPath("//*[#id=\"browse-deals\"]");
TagNode dealWrapper = (TagNode) objects[0];
//Get the childs
TagNode[] todayDeals = dealWrapper.getElementsByAttValue("class", "deal-list-tile grid_5_third", true, true);
System.out.println("++++ Groupon Deal Today: " + todayDeals.length + " deals");
for (int i = 0; i < todayDeals.length; i++) {
String link = String.format("http://www.groupon.com%s", todayDeals[i].findElementByAttValue("class", "deal-permalink", true, true).getAttributeByName("href").toString());
arrayList.add(link);
}
return arrayList;
} catch (Exception e) {
System.out.println("Error parsing Groupon:" + e.getMessage());
e.printStackTrace();
}
return null;
}
For me adding the 'User-Agent' solves the problem; use it like this snippet:
final URL urlSB = new URL("http://www.groupon.com/browse/chicago?z=skip");
final URLConnection urlConnection = urlSB.openConnection();
urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
urlConnection.connect();
final HtmlCleaner cleaner = new HtmlCleaner();
final CleanerProperties props = cleaner.getProperties();
props.setNamespacesAware(false);
final TagNode tagNodeRoot = cleaner.clean(urlConnection.getInputStream());