I'm new to Java and I'm trying to create a lib for fetching Brazilian addresses from a webservice but I can't read the response.
in the constructor of the class I have this result string to which I want to append the response, once this variable is populated with the response I will know what to do.
The problem is: for some reason, I guess the BufferedReader object is not working so there is no response to be read :/
Here is the code:
package cepfacil;
import java.net.*;
import java.io.*;
import java.io.IOException;
public class CepFacil {
final String baseUrl = "http://www.cepfacil.com.br/service/?filiacao=%s&cep=%s&formato=%s";
private String zipCode, apiKey, state, addressType, city, neighborhood, street, status = "";
public CepFacil(String zipCode, String apiKey) throws IOException {
String line = "";
try {
URL apiUrl = new URL("http://www.cepfacil.com.br/service/?filiacao=" + apiKey + "&cep=" +
CepFacil.parseZipCode(zipCode) + "&formato=texto");
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(apiUrl.openStream()));
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
System.out.println(line);
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.zipCode = zipCode;
this.apiKey = apiKey;
this.state = state;
this.addressType = addressType;
this.city = city;
this.neighborhood = neighborhood;
this.street = street;
}
}
So here is how the code is supposed to work, you build an object like this:
String zipCode = "53416-540";
String token = "0E2ACA03-FC7F-4E87-9046-A8C46637BA9D";
CepFacil address = new CepFacil(zipCode, token);
// so the apiUrl object string inside my class definition will look like this:
// http://www.cepfacil.com.br/service/?filiacao=0E2ACA03-FC7F-4E87-9046-A8C46637BA9D&cep=53416540&formato=texto
// which you can check, is a valid url with content in there
I've omitted some parts of this code for brevity but all the methods called in the constructor are defined in my code and there is no compilation or runtime error going on.
I'd appreciate any help you could give me and I'd love to hear the simplest posible solutions :)
Thanks in advance!
UPDATE: now that I could fix the problem (huge props to #Uldz for pointing me the problem out) it is open sourced http://www.rodrigoalvesvieira.com/cepfacil/
In
System.out.println(line + "rodrigo");
you output line not the result. Maybe last line is empty?
There could be multiple reasons.
wrap your URL in HttpURLConnection, this will help you to see the response code and more info on response you get from server.
You could/should add an encoding to InputStreamReader.
And then result does not add newlines.
BufferedReader in = new BufferedReader(new InputStreamReader(apiUrl.openStream()));
while ((line = in.readLine()) != null) {
System.out.println("Line: " + line);
String[] keyValue = line.split("\\s*=\\s*", 2);
if (keyValue.length != 2) {
System.err.println("*** Line: " + line);
continue;
}
switch (keyValue[0]) {
case "status":
status = keyValue[1];
break;
...
default:
System.err.println("*** Key wrong: " + line);
}
result += line + "\n";
}
in.close();
Related
I'm trying to pass the contents of a file into a method as a String and encountering a Null pointer exception. I'm converting the file into a String like so:
import java.io.*;
public class FileHandler {
String inputText = null;
public String inputReader() {
StringBuilder sb = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
String inputText = sb.toString();
//System.out.println(inputText);
}
br.close();
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
}
return inputText;
}
}
This is working fine for me in terms of converting the file to a String, but when I try and pass the output of this into another method I get a null pointer exception here:
char[][] railMatrix = new char[key][inputText.length()];
I copied the contents of the file and passed it in as a normal String like so;
String plain = "The text from the file"
int key = 5;
int offset = 3;
String encrypted = rf.encrypt(plain, key, offset);
System.out.println(encrypted);
String unencrypted = rf.decrypt(encrypted, key, offset);
System.out.println(unencrypted);
And it worked fine. But
String plain = fh.inputReader();
Does not.
So inputReader() seems to work, the methods it's being passed into work, but I'm clearly missing something.
A nod in the right direction would be greatly appreciated, thanks friends.
Your result is stored in a local variable "inputText" and you are returning instance level variable which is null and is never reassigned. Remove String type as below and it should work:
while ((line = br.readLine()) != null) {
sb.append(line);
inputText = sb.toString();
//System.out.println(inputText);
}
I am trying to use this api to get report with java, and here is the link
https://developers.google.com/admin-sdk/reports/v1/appendix/activity/meet
and here is what i am using now
public static String getGraph() {
String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?eventName=call_ended&maxResults=10&access_token=";
String graph = "";
try {
URL urUserInfo = new URL(PROTECTED_RESOURCE_URL + "access_token");
HttpURLConnection connObtainUserInfo = (HttpURLConnection) urUserInfo.openConnection();
if (connObtainUserInfo.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuilder sbLines = new StringBuilder("");
BufferedReader reader = new BufferedReader(
new InputStreamReader(connObtainUserInfo.getInputStream(), "utf-8"));
String strLine = "";
while ((strLine = reader.readLine()) != null) {
sbLines.append(strLine);
}
graph = sbLines.toString();
}
} catch (IOException ex) {
x.printStackTrace();
}
return graph;
}
I am pretty sure it's not a smart way to do that and the string I get is quite complex, are there any jave sample that i can get the data directly instead of using java origin httpRequest
Or, are there and class I can import to switch the json string to the object!?
Anyone can help?!
I have trying this for many days already!
Thanks!!
I have a strange problem. I have in the past used a program I wrote myself to check if a new chapter has come out on a story at fanfiction.net and that program works fine even now (though its GUI leaves a lot to wish for).
However, when I am trying to make a new version I can't seem to load the webpage even though I'm using the exact same code (Copy Pasted). This is the code below. When sending in a URL like https://www.fanfiction.net/s/11012678/36 to the nextExists method it should return 'true'. My old program does, but this one doesn't even though it's the same code.
The only thing I can think of that might have any effect would be that I am using a new version of Eclipse which might cause it to mistake the Encoding, but I have tried checking all the common encoding types and nothing provides the HTML plaintext.
Does anyone have any idea what might be causing this? It's not a disaster if I can't get this right but I would like to know for the future in case I run into the same problem again.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class Util {
private static final String BEFORE = "<button class=btn TYPE=BUTTON onClick=\"self.location='", AFTER = "'\">Next ></button>", SITE = "fanfiction.net";
public static String readSite(String path) throws Exception{
URL url = new URL(path);
BufferedReader in = null;
String line;
try{
StringBuilder builder = new StringBuilder();
in = new BufferedReader(new InputStreamReader(url.openStream()));
line = in.readLine();
if(line == null){
return null;
}
builder.append(line);
while((line = in.readLine()) != null){
builder.append('\n' + line);
}
return builder.toString();
} finally{
if(in != null){
in.close();
}
}
}
public static String updatePathToEnd(String path) throws Exception{
outer: while(nextExists(path)){
String data = readSite(path);
if(path.contains(SITE)){
String link = path.substring(0, path.indexOf(SITE) + SITE.length()) + data.substring(data.indexOf(BEFORE) + BEFORE.length(), data.indexOf(AFTER));
if(readSite(link) != null) {
path = link;
continue outer;
}
}
}
return path;
}
public static boolean nextExists(String path) throws Exception{
String text = readSite(path);
if(path.contains(SITE)){
return text==null ? false : text.contains(AFTER);
}
return false;
}
}
I tried in bluej and works perfect, it seems that the problem is in Eciplse
Regards
I'm writing a program where I get information from a page and put it in excel file.
The problem is, I don't find a way to search for the tag with the specific info.
Here is my code(so far):
private void getAll() throws IOException {
for (int i = 0;i<250;i++){
URL vurl = new URL("http://www.bamart.be/nl/artists/detail/" + i);
BufferedReader reader = new BufferedReader(new InputStreamReader(vurl.openStream()));
String line;
while ((line = reader.readLine()) != null){
if (line.equalsIgnoreCase("<div class=\"subcontent\">"){
System.out.println("Found info!");
}
printInfo(line,i);
}
}
}
private void printInfo(String info,int i){
System.out.println("/***********************************************/");
System.out.println("************\t" + info + "**********************/");
System.out.println("/************" +" Artist page:" + i + " of 999 **********************/" );
}
The println doesn't come up, but it is in the html file.
if (line.equalsIgnoreCase("<div class=\"subcontent\">"){ }
This if statement is checking for exact equality (ignoring case) however there could be other content on that line including whitespace for example.
What you might want instead would be something like
if (line.toLowerCase().contains("<div class=\"subcontent\">") { }
Try using Jsoup starting with this example
How do I create a Java program that enters the words "Hello World" into Google and then retrieves the html from the results page? I'm not trying to use the Robot class.
URL url = new URL("http://www.google.com/search?q=hello+world");
url.openStream(); // returns an InputStream which you can read with e.g. a BufferedReader
If you make repeated programmatic requests to Google in this way they will start to redirect you to "we're sorry but you look like a robot" pages pretty quick.
What you may be better doing is using Google's custom search api.
For performing google search through a program, you will need a developer api key and a custom search engine id. You can get the developer api key and custom search engine id from below urls.
https://cloud.google.com/console/project'>Google Developers Console
https://www.google.com/cse/all'>Google Custom Search
After you got the both the key and id use it in below program. Change apiKey and customSearchEngineKey with your keys.
For step by step information please visit - http://www.basicsbehind.com/google-search-programmatically/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class CustomGoogleSearch {
final static String apiKey = "AIzaSyAFmFdHiFK783aSsdbq3lWQDL7uOSbnD-QnCnGbY";
final static String customSearchEngineKey = "00070362344324199532843:wkrTYvnft8ma";
final static String searchURL = "https://www.googleapis.com/customsearch/v1?";
public static String search(String pUrl) {
try {
URL url = new URL(pUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String buildSearchString(String searchString, int start, int numOfResults) {
String toSearch = searchURL + "key=" + apiKey + "&cx=" + customSearchEngineKey + "&q=";
// replace spaces in the search query with +
String newSearchString = searchString.replace(" ", "%20");
toSearch += newSearchString;
// specify response format as json
toSearch += "&alt=json";
// specify starting result number
toSearch += "&start=" + start;
// specify the number of results you need from the starting position
toSearch += "&num=" + numOfResults;
System.out.println("Seacrh URL: " + toSearch);
return toSearch;
}
public static void main(String[] args) throws Exception {
String url = buildSearchString("BasicsBehind", 1, 10);
String result = search(url);
System.out.println(result);
}
}