URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
System.out.print(code);
if (code==200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
String content = in.toString();
System.out.print(content);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(new InputStreamReader(in, "UTF-8"));
result = (String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
}
When I have a host string like http://www.example.com/json.txt it all works fine, but when I have host string like www.example.com/index.php?data=data&data2=data2 I get the following error:
W/System.err: Unexpected character () at position 0.
I/System.out: 200java.io.BufferedInputStream#8bc189fpp = [0, 700, 250, 700]
My PHP output in browser looks fine, when I copy it to json.txt it also works fine.
I try to play with urlConnection POST, GET, RAW without luck.
Any ideas?
Problem was probly BOM in php json.
I do:
URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
System.out.print(code);
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringWriter writer = new StringWriter();
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
result = result.substring(1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(result);
result=(String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
}
And it works.
Related
I have been trying all day to get a minecraft plugin to allow players on bedrock edition on my geyser sever to (OPTIONALY) sign in to java edition using OAuth2's device code flow. I successfully can get a code and url but when I go to poll the API for a successful login I get "Cross-origin token redemption is permitted only for the 'Single-Page Application'." I've tried adding SPA to my azure app registration but the issue persists. I've tried setting the origin header in my request to "http://localhost" and the issue persist:
here is my code for retrieving the login token:
public static JSONObject pollSignIn(String deviceCode) {
double i = 0;
long previousTime = 0;
while (i <= 60000 /*GeyserFloodgateSkinFix.defaultConfig.requestTimeout*/) {
while (!(System.currentTimeMillis() > previousTime)) {}
previousTime = System.currentTimeMillis();
i++;
if ((i/1000) % 3 == 0) {
try {
URL url = new URL("https://login.microsoftonline.com/common/oauth2/v2.0/token");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Origin", null);
con.setDoOutput(true);
System.out.println(deviceCode);
String body = String.format(
"grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=%s&device_code=%s",
"[Censored]",
deviceCode
);
byte[] output = body.getBytes(StandardCharsets.UTF_8);
OutputStream os = con.getOutputStream();
os.write(output);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(br.readLine());
}
JSONObject json = new JSONObject(sb.toString());
if (json.getString("token_type").equalsIgnoreCase("Bearer")) {
return json;
}
}
catch (Exception ignored) {
System.out.println(ignored.getMessage());
}
}
}
return null;
}
if it helps heres the code I use to get the token (This works)
public static JSONObject getAuthCode() {
try {
URL url = new URL("https://login.microsoftonline.com/common/oauth2/v2.0/devicecode");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
String body = String.format(
"scope=XboxLive.signin%%20offline_access&client_id=%s",
"[Censored]"
);
OutputStream os = con.getOutputStream();
byte[] output = body.getBytes(StandardCharsets.UTF_8);
os.write(output, 0, output.length);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
con.disconnect();
return new JSONObject(sb.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
UPDATE: I managed to fix the above error but now I am getting "The provided value for the input parameter 'scope' is not valid. The scope 'XboxLive.signin offline_access' is not configured for this tenant." Chanfing the tenant to "consumer" throws "The provided value for the input parameter 'device_code' is not valid. Device codes supporting the personal Microsoft Account sign-in audience can only be used for v2 common or consumers tenants"
How do I parse an array of JSON objects from an external URL with the Java application? Here is an example of code, that I am using:
URL connectionUrl = new URL(/*some url*/);
connection = (HttpURLConnection) connectionUrl.openConnection();
String postData = "/*some post data*/";
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(postData.length());
OutputStream outputStream = null;
outputStream = connection.getOutputStream();
outputStream.write(postData.getBytes());
if(connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String magicString = "", magicLine;
while((magicLine = bufferedReader.readLine()) != null) {
JSONArray jsonArr = new JSONArray(magicLine);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject currentEntity = jsonArr.getJSONObject(i);
}
}
return magicString;
And this one is the array of JSON objects, that gets echo'd out on some external URL:
[{"ID":"1","name":"test name","phone":"+37120000000","email":"test#cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"0"},{"ID":"2","name":"test name","phone":"+37120000000","email":"test#cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"1"}]
Unfortunately, the application fails with the following error:
org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONArray
You can create a POJO to hold JSON response. Use third-party jar such as Jackson. Something like the following:
ObjectMapper mapper = new ObjectMapper();
try {
YourPOJO obj = mapper.readValue(new URL("http://jsonplaceholder.typicode.com/posts/7"), YourPOJO.class);
System.out.println(usrPost);
} catch (Exception e) {
e.printStackTrace();
}
Refer to https://www.java2novice.com/java-json/jackson/jackson-client-read-from-api-url/
I have a text file where i am trying to fetch data one by one and store it in rri section with current time stamp under one PUT call but currently its fetching only one value or multiple request? Kindly help me to get through it. I will be sharing the text file and expected result in the comment section below.
File file = new File("DataToInput.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String urlString= "http://34.237.64.52 /v1/iot-hitoe-analytics/groups/0d98a4d3-207c-41e3-a943-363b73d58adf/raw-data";
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("PUT");
//conn.connect();
conn.setRequestProperty("content-type", "application/json");
conn.setRequestProperty("Accept", "application/json");
JSONObject Main = new JSONObject();
JSONArray alldata = new JSONArray();
JSONObject alldata1 = new JSONObject();
JSONObject metadata = new JSONObject();
metadata.put("sensorTypeId", sensorTypeId);
metadata.put("sensorId", sensorId);
metadata.put("sensorName", sensorName);
metadata.put("connectionMode",connectionMode);
JSONObject owner = new JSONObject();
owner.put("groupId", groupId);
owner.put("entityId", entityId);
JSONObject sensordata = new JSONObject();
JSONObject rawRri = new JSONObject();
JSONArray samples_rri = new JSONArray();
JSONObject samples1_rri = new JSONObject();
while ((line = bufferedReader.readLine()) != null) {
String[] fields = line.split(" ");
// System.out.println("fields size is "+fields.length);
// System.out.println("fields value is "+fields[0]);
stringBuffer.append(line);
stringBuffer.append("\n");
}
samples1_rri.put("rri",line);
samples1_rri.put("timestamp",System.currentTimeMillis());
samples_rri.put(samples1_rri);
rawRri.put("samples", samples_rri);
sensordata.put("rawRri", rawRri);
alldata1.put("metadata", metadata);
alldata1.put("owner", owner);
alldata1.put("sensordata", sensordata);
alldata.put(alldata1);
Main.put("alldata", alldata);
String payload = Main.toString();
ObjectMapper mapper = new ObjectMapper();
#SuppressWarnings("unused")
Object json = mapper.readValue(payload, Object.class);
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
System.out.println(indented);
/*OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(indented);
writer.close();*/
fileReader.close();
bufferedReader.close();
//System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
URLEncoder.encode(urlString,"UTF-8");
System.out.println("response codec: "+conn.getResponseCode());
// if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
// throw new RuntimeException("Failed : HTTP error code : "
// + conn.getResponseCode());
System.out.println("response received!!");
}
else {
System.out.println("response: "+conn.getInputStream());
}
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br1.readLine()) != null) {
System.out.println(output);
}
Error:
E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
I have to send image to server with post method but I cant send. Json came to me null. There is my code:
if (method.equalsIgnoreCase("POST")) {
URL url_ = new URL(url);
String paramString = URLEncodedUtils.format(params, "utf-8"); // unused
HttpURLConnection httpConnection = (HttpURLConnection) url_.openConnection();
httpConnection.setReadTimeout(10000);
httpConnection.setConnectTimeout(15000);
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
InputStream in = httpConnection.getInputStream();
OutputStream out = new FileOutputStream(picturePath);
copy(in, out);
out.flush();
out.close();
httpConnection.connect();
//Read 2
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
String line2 = null;
StringBuilder sb = new StringBuilder();
while ((line2 = br.readLine()) != null) {
sb.append(line2);
}
br.close();
json = sb.toString();
}
How can I send image to server?
Thanks..
I am sorry to post such a "noob question", but I can't solve my problem by myself.
I have a server-side script, written in php which returns different values, in this example all companynames which are stored in a MySQL DB.
-The column in the DB is encoded in UTF-8
-The php file is encoded in UTF-8
This is the server side script:
include_once('SQLHandler.php');
$SQLHandler = new SQLHandler();
if(isset($_POST['command'])){
$command = $_POST['command'];
switch($command){
case 'getCompanies':
echo utf8_encode('[["Test1"],["Test2"],["Test3"],["Test4"]]');
//echo json_encode( $SQLHandler -> getCompanies());
break;
}
}
it returns "[["Test1"],["Test2"],["Test3"],["Test4"]]".
However, when I want to analyze the returned String and parse it to an array (with json-simple library), the following occurs:
?[["Test1"],["Test2"],["Test3"],["Test4"]]
Unexpected token END OF FILE at position 0.
The Java Code is the following:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = rd.readLine()) != null){
System.out.println(line);
}
String jsonText = readAll(rd);
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(jsonText);
System.out.println(array);
System.out.println(array.toJSONString());
System.out.println(array.toString());
} catch(Exception e){
e.printStackTrace();
}
return null;
It is my first time working with java and json, so it is possible that I did a very easy to find error, but I would be very thankfull if you could point it out to me (and explain what I did wrong;))
Regards
Well, turns out it wasn't an encoding problem at all...
See my modified code:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String wholeLine = "";
String line;
while ((line = rd.readLine()) != null) {
wholeLine = wholeLine + line;
}
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(wholeLine);
for(Object obj : array.toArray()){
System.out.println(obj.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
I forgot to supply "line" to the parse function and instead parsed the wrong variable ^^
Regards