How to get connection with API using JFrame - java

I am working on an English dictionary using an online free API: https://api.dictionaryapi.dev/api/v2/entries/en_US/
The code was working fine just one month ago, but now the returned data is always "error". It is not giving back response :: 200. Could anyone tell me what's wrong with the code?
public String getOnlineData(String word){
String data = "";
String decodeData = "";
try{
URL url = new URL("https://api.dictionaryapi.dev/api/v2/entries/en_US/"+word);//store the url link in the variable url
HttpURLConnection con = (HttpURLConnection)url.openConnection();//start a new connection
if(con.getResponseCode()==200){
InputStream im = con.getInputStream();//store the text result in the variable im
BufferedReader br = new BufferedReader(new InputStreamReader(im));
//read the result using bufferedreader
String line=br.readLine();//read each line
while(line!=null){//stop until there is no line to read
data = data + line;
line=br.readLine();
}
br.close();//close the buffered reader
decoder jd = new decoder();//decode the result
decodeData = jd.Decoder(data);//store the decoded result in decodeData
}
else{
decodeData="error";//if the system doesn't get response, the result will be error
}
}
catch(Exception e){
try{
decodeData="error";//if the connection failed, result is error
System.out.println(e);
}
catch(Exception e1){
System.out.println(e1);
}
}
return decodeData;
}

Related

ImageIO.readImage IIOException while I can open it in Chrome

I can open this image in my browser but it won't load in my java application, why? It is supposed to be a free-to-use database, I can't see why I can't use it.
I'm using this piece of code:
public static String getContentsFromURL(String address){
String contents = "";
try{
URL url = new URL(address);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while((line = bufferedReader.readLine()) != null){
contents += line;
}
bufferedReader.close();
}catch(IOException e){
e.printStackTrace();
}
return contents;
}
And I'm getting an IIOException "Can't find input file!"
try this code
URL url = new URL("http://ddragon.leagueoflegends.com/cdn/9.20.1/img/champion/Gragas.png");
Image image1 = ImageIO.read(url);
image screenshot from my debbuger.

How can i transform String from URL to JSON?

So, basically i have this function:
public String ReadingURL(String IncomingURL){
String prueba = "";
try{
URL url = new URL (IncomingURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while((line = in.readLine()) != null){
prueba+=prueba;
}
in.close();
return prueba;
}
catch (MalformedURLException e){
System.out.println("Malformed URL: "+ e.getMessage());
return "Error";
}
catch(IOException e){
System.out.println("I/O Error: " + e.getMessage());
return "Error";
}
}
It's supposed to read line by line of an URL and extract the content.
What this URL is gonna contain is basically a JSON Object but like in plain text, what i need to do is to grab
"prueba" that contains the content of the URL and convert that into an actual JSON Object so i can later send a print command with the contents of that JSON .
I'm new to JSON so be gentle haha

I cant insert data from a java program to laravel app via api

I am new to laravel and I would like to save data to my online server via laravel api from a java program but I am getting errors.
this is my route on api.php:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('hooks','ApiTestController#store');
my ApiTestController: its just handles POST request then saves to the table.
public function store(Request $request)
{
$postdata = json_decode($request->input('post_data'), true);
$datas = $postdata['header'];
$data = $datas[0];
$testH = new TestH();
$testH->test_date = $data['test_date'];
$testH->expiration = $data['test_date'];
$testH->source = $data['source'];
$testH->save();
return $testH;
}
and my java code :
try {
//local development server url
URL url = new URL("http://127.0.0.1:8000/api/hooks");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
//create the JSON String
String json = null;
StringWriter sw = new StringWriter();
JSONWriter wr = new JSONWriter(sw);
try {
wr.object().key("header").array();
wr.object();
wr.key("test_date").value(new Date());
wr.key("source").value("TEST");
wr.key("expiration").value(new Date());
wr.endObject();
wr.endArray().endObject();
json = sw.toString();
System.out.println(json);
} catch (JSONException ex) {
Logger.getLogger(WebConnectSample.class.getName()).log(Level.SEVERE, null, ex);
}
// send to laravel server
ps.print("post_data="+json);
HttpURLConnection httpConn = (HttpURLConnection) con;
InputStream is;
if (httpConn.getResponseCode() >= 419) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
// read the server reply
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
// close the print stream
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
the thing is when I dont save via $testH->save() everything works fine. but if I include it java returns with the following error:
Type error: Argument 1 passed to Illuminate\Routing\Middleware\ThrottleRequests::addHeaders() must be an instance of Symfony\Component\HttpFoundation\Response, string given, called in C:\Users\relixusdev\Documents\WebProjects\tcmsite\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php on line 61
any idea what part causes the error? does it have to do with authentication? i just want to be able to save to the online database via my java program.
Try using Route group with prefix as below
Route::group(['prefix' => 'api'], function() {
Route::post('hooks','ApiTestController#store');
});
if anyone comes here having the same problem, i found out that the problem is that I dont have the created_at and updated_at column at my table. I didn't realized its a requirement for laravel. silly me.

Grabbing JSON works from one link, not from another

I'm doing a simple JSON grab from two links with the same code. I'm doing it two separate times, so the cause of my issue isn't because they're running into each other or something.
Here is my code:
#Override
protected String doInBackground(Object... params) {
try {
URL weatherUrl = new URL("my url goes here");
HttpURLConnection connection = (HttpURLConnection) weatherUrl
.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
Log.v("test", responseData);
When I try this with:
http://www.google.com/calendar/feeds/developer-calendar#google.com/public/full?alt=json
I get an error of having an array lenth of -1
For this link:
http://api.openweathermap.org/data/2.5/weather?id=5815135
It returns fine and I get a log of all of the JSON. Does anyone have any idea why?
Note: I tried stepping through my code in debug mode, but I couldn't catch anything. I also downloaded a Google chrome extension for parsing json in the browser and both urls look completely valid. I'm out of ideas.
Log this: int contentLength = connection.getContentLength();
I don't see the google url returning a content-length header.
If you just want String output from a url, you can use Scanner and URL like so:
Scanner s = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A");
out = s.next();
s.close();
(don't forget try/finally block and exception handling)
The longer way (which allows for progress reporting and such):
String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
} catch (IOException e) {
// Handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// Handle exception
}
}
return sb.toString();
}
}
and then call String response = convertStreamToString( inputStream );

Error when using java.net to connect to a website

I am trying to login to a website using java.net in Google App Engine for Java.
The login id and password are stored in variables 'loginid' and 'password' respectively.
The code that I have created is given below:
public Integer login()
{
String param1="", param2="", query="";
String charset = "UTF-8";
String loginurl = "https://website.com/login";
try {
param1 = URLEncoder.encode(loginid, "UTF-8");
param2 = URLEncoder.encode(password, "UTF-8");
query = String.format("username=%s&password=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
} catch (UnsupportedEncodingException ex) {
// ...
}
try {
URL url = new URL(loginurl + "?" + query);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line="";
String resp="";
while ((line = reader.readLine()) != null) {
resp=resp + line;
}
actionmessage=" Response-" + resp;
return(1);
}
catch (Exception e) {
// ...
}
}
I want to know more about a couple of things with ref to above code.
I am sure that I have entered correct ID and password, but still I am getting login failure. What is wrong with the above code?
How do I check if a submission as made by above code is successful or if there is an error? If there is an error, how do I get the error stream?
It was an error on my part- I encoded the 2 parameters passed to input url, twice!! So the site where I was authenticating, received a garbled value for user id and password!

Categories