I am currently coding in Java using Eclipse. I am trying to obtain the value of the key "high" given the data
{"high": "639.00000", "last": "634.94000", "timestamp": "1476220216", "bid": "634.94000", "vwap": "630.07099", "volume": "7939.75947138", "low": "613.83000", "ask": "636.50000", "open": "616.37000"}
which I get from this address : "https://www.bitstamp.net/api/v2/ticker/btcusd/"
So far, I got this code:
package JsonSimpleExample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.*;
public class JsonSimpleExample {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.bitstamp.net/api/v2/ticker/btcusd/");
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println(br.readLine());
}
}
A possible solution is to write the data I get from the website into a file and input each key, value pair into a hashmap and call for the value but that seems very highly redundant. Is there any way to directly obtain a value for a key with the data that the API gives me?
Simple you need to add json library also.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONObject;
/**
*
* #author BTACTC
*/
public class JsonExample {
URL url;
String str;
Scanner scan;
JSON json;
public JsonExample() throws MalformedURLException, IOException {
url = new URL("https://www.bitstamp.net/api/v2/ticker/btcusd/");
scan = new Scanner(url.openStream());
str = new String();
while (scan.hasNext()) {
str += scan.nextLine();
}
System.out.println(str);// checking the data is now in string
JSONObject obj = new JSONObject(str);
System.out.println(obj.getString("high"));;
}
public static void main(String[] args) throws IOException {
JsonExample JE = new JsonExample();
}
}
Related
I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want.
I tried many approaches. some of are:
package main;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PrnToHtml {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn"));
FileWriter writer = new FileWriter("output_prn.html")) {
writer.write("<html><body><h3>PRN to HTML</h3><table border>\n");
String currentLine;
while ((currentLine = reader.readLine()) != null) {
writer.write("<tr>");
for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}"
writer.write("<td>" + field + "</td>");
writer.write("</tr>\n");
}
writer.write("</table></body></html>\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of this will be html page looks like this:
prn file\data looks like this:
Other this I tried to read this is:
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PRNToHtml {
private static final String DILIM_PRN = " ";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
try (#SuppressWarnings("resource")
Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) {
List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
for (String[] strings : inputValuesInLines) {
for (String s : strings) {
System.out.print(s.replaceAll("\\s+", "") + " ");
}
System.out.println();
}
}
}
}
output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this:
Help will be appreciated.
Thank you :)
My java code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class celebGrepper {
static class CelebData {
URL link;
String name;
CelebData(URL link, String name) {
this.link=link;
this.name=name;
}
}
public static String grepper(String url) {
URL source;
String data = null;
try {
source = new URL(url);
HttpURLConnection connection = (HttpURLConnection) source.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
/**
* Attempting to fetch an entire line at a time instead of just a character each time!
*/
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while((data = br.readLine()) != null)
str.append(data);
data=str.toString();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static ArrayList<CelebData> parser(String html) throws MalformedURLException {
ArrayList<CelebData> list = new ArrayList<CelebData>();
Pattern p = Pattern.compile("<td class=\"image\".*<img src=\"(.*?)\"[\\s\\S]*<td class=\"name\"><a.*?>([\\w\\s]+)<\\/a>");
Matcher m = p.matcher(html);
while(m.find()) {
CelebData current = new CelebData(new URL(m.group(1)),m.group(2));
list.add(current);
}
return list;
}
public static void main(String... args) throws MalformedURLException {
String html = grepper("https://www.forbes.com/celebrities/list/");
System.out.println("RAW Input: "+html);
System.out.println("Start Grepping...");
ArrayList<CelebData> celebList = parser(html);
for(CelebData item: celebList) {
System.out.println("Name:\t\t "+item.name);
System.out.println("Image URL:\t "+item.link+"\n");
}
System.out.println("Grepping Done!");
}
}
It's supposed to fetch the entire HTML content of https://www.forbes.com/celebrities/list/. However, when I compare the actual result below to the original page, I find the entire table that I need is missing! Is it because the page isn't completely loaded when I start getting the bytes from the page via the input stream? Please help me understand.
The Output of the page:
https://jsfiddle.net/e0771aLz/
What can I do to just extract the Image link and the names of the celebs?
I know it's an extremely bad practice to try to parse HTML using regex and is the stuff of nightmares, but on a certain video training course for android, that's exactly what the guy did, and I just wanna follow along since it's just in this one lesson.
If a user don't have any web browser, which java code he should write (and which classes he needs) to download and read file? Lets say that this is the URL where the file will be downloaded:
http://www.thewebsource.serv/dir1/myfile.txt
So far I have tried to access a url, but in order to download a file what procedure I should follow.
package filedownload;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class FileDownload {
public static void main(String[] args) throws URISyntaxException, IOException {
Desktop d=Desktop.getDesktop();
d.browse(new URI("http://www.thewebsource.serv/dir1/myfile.txt"));
}
}
You could use something like this using the URL class:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
From java doc tutorials: Link
I have This code and I tried to getting items from this string
but it's failed
I have used eclipse IDE
I have parsing the json string from remote host
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String line;
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
try{
JSONObject jObject = new JSONObject(s);
String projecname=(String) jObject.get("name");
System.out.print(projecname);
}catch(Exception e)
{}
}
}
the result Json string is like this
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
please help me
thanks
You have to parse the json string into JSONObject using JSONParser
You cannot simply parameterise JSONObject with a string.
So you have to do:
JSONParser parser = new JSONParser();
JSONObject jObject=(JSONObject)parser.parse(jsonstr);
String projecname=(String) jObject.get("name");
I am currently trying to build a client application for twitter. One of the functionalities of the app is to search tweet (including historical tweet). I tried to modify the code that I got from Github. However, when I tried to debug the code, I got JSONException cause by null value. Here is my code:
package thematicanalysis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import twitter4j.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import twitter4j.JSONException;
/**
*
* #author adichris
*/
public class TweetManager {
private static String getURLResponse(String since, String until, String querySearch, String scrollCursor,int counter) throws Exception{
String appendQuery = " ";
if(since!=null)
appendQuery+= " since:"+since;
if(until!=null)
appendQuery+= " until:"+until;
if(querySearch!=null)
appendQuery+= " "+querySearch;
String url = String.format("https://twitter.com/search?src=typd&q=%s&scroll_cursor=%s", URLEncoder.encode(appendQuery, "UTF-8"),scrollCursor);
System.out.println("URL: "+ url);
URL obj = new URL (url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
//StringBuilder response;
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine=in.readLine())!=null)
response.append(inputLine);
in.close();
con.disconnect();
//System.out.println(response.toString());
saveToFile(response.toString(),counter);
return response.toString();
}
private static void saveToFile(String content,int counter) throws IOException
{
try (PrintWriter pw = new PrintWriter("newOutput"+counter+".txt","UTF-8")) {
pw.printf("%s\n",content);
pw.close();
}
}
public static void getTweets (String since, String until, String querySearch) throws JSONException, Exception{
try{
String refreshCursor = null;
int counter = 1;
while(true)
{
String response = getURLResponse(since,until,querySearch,refreshCursor,counter);
JSONObject json = new JSONObject(response);
if(json.equals(null))
System.out.println("hereeee");
counter++;
System.out.println(counter);
refreshCursor = json.getString("scroll_cursor");
Document doc = Jsoup.parse((String)json.get("items_html"));
Elements tweets = doc.select("div.js-stream-tweet");
System.out.println(tweets.size());
if (tweets.isEmpty()){
break;
}
for (Element tweet: tweets){
String userName = tweet.select("span.username.js-action-profile-name b").text();
String text = tweet.select("p.js-tweet-text").text().replaceAll("[^\\u0000-\\uFFFF]", "");
long dateMs = Long.valueOf(tweet.select("small.time span.js-short-timestamp").attr("data-time-ms"));
Date date = new Date(dateMs);
System.out.println(userName);
//saveToFile(text);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}
}