I have been working with java to make it where i check if a certain user if live and it will say true or false if the user is streaming...im working with minimal json.
here is my code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import com.eclipsesource.json.JsonObject;
public class hostbot {
public static void main(String[] args) throws Exception {
Twitchbot bot = new Twitchbot();
bot.setVerbose(true);
bot.connect("irc.twitch.tv", 6667, "something");
}
public boolean isStreamLive()
{
try
{
URL url = new URL("https://api.twitch.tv/kraken/streams/rexephon");
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject jsonObj = JsonObject.readFrom(inputLine);
return ( jsonObj.get("stream").isNull() )?false:true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
}
when i return false is that suppose to print in the log the word false? or something else?
Related
I'm using JSON and want to send post request to server via username, password in body and x-auth-app-id, x-auth-app-hash in header..
I have test on Postmen and it return 200 (status ok), But when I build my sources it happen error.
This is my class header:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpRequestUtil {
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
InputStream inputStream=null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestProperty("x-auth-app-id", "6166611659356156223");
httpUrlConn.setRequestProperty("x-auth-app-hash", "a44f4ea21475fa6761392ba4bc659990bee771c413b2c207490a79f9ec78c2a61234");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
httpUrlConn.setRequestMethod(requestMethod);
if ("POST".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}
catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("Our server connection timed out");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("https request error:{}");
}
finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}
}
And class Body:
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class CallCenterController {
public static void main(String[] args) throws JSONException {
String sipUser = "vchi_dd";
String sipPassword = "m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa";
Map<String, Object> sipAccount = new HashMap<String, Object>();
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
sipAccount = postData(sipUser, sipPassword);
System.out.println("result: " + sipAccount);
};
public static JSONObject postData(String sipUser, String sipPassword) {
String url="https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser="+sipUser+"&sipPassword="+sipPassword;
return HttpRequestUtil.httpRequest(url, "POST", "");
}
}
When I build it happen an exception following as:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser=vchi_dd&sipPassword=m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa
https request error:{}
result: null
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.mypackage.HttpRequestUtil.httpRequest(HttpRequestUtil.java:63)
at com.mypackage.CallCenterController.postData(CallCenterController.java:45)
at com.mypackage.CallCenterController.main(CallCenterController.java:34)
How to send correct data to my url and fix the problem?
I would use Java HTTP Client API if your java version is high enough.
Here's a link to it https://www.baeldung.com/java-9-http-client
I have used it and it feels more maintainable and clear.
Also, it seems that you're sending the request with empty body even though you say in your question that you are sending username and password in body.
And why are you adding username and password to a map if you are not using the map?
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
below code is for getting html web page
import java.net.*;
import java.io.*;
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class TestClass2 {
public static void main(String[] args) throws Exception {
try{
URL url = new URL("https://stackoverflow.com/");
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line+"\n");
}
reader.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
but when compile and run that below error occur:
javax.net.ssl.SSLException: Received fatal alert: protocol_version.
how can fix it?
thanks.
This could be that the SSL Certificate is out of date? Have you tried using HttpsURLConnection? Try this first
Revised Code
import java.net.*;
import java.io.*;
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class TestClass2 {
public static void main(String[] args) throws Exception {
try{
URL url = new URL("https://stackoverflow.com/");
HttpsURLConnection urlConnection=(HttpsURLConnection)url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line+"\n");
}
reader.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
It took me a long time to get the proxy for my Java connection working at my office. Now I got it working, but it's VERY slow.
I use the following code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class Test {
public static void main(String[] args) {
long millis = System.currentTimeMillis();
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("xxxx",
"xxxx".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
url = new URL("http://stackoverflow.com/");
URLConnection conn = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("xxx", xxx)));
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
System.out.println("Duration: "+(System.currentTimeMillis()-millis));
}
}
When I run this, the output is the following:
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
Duration: 222856
As you can see, the proxy is working. I do get the webpage just fine. But it's waiting very long before showing the webpage contents (more than 222 seconds :O). I have no clue what could possibly be the problem here.
Just some information about the environment: I'm working on my office VDI. Google Chrome and IE have internet connection, but other programs don't. By a lot of googling I found the correct proxy settings.
I am practising JUnit test cases and currently working on a problem which is as follows:
To read HTML from any website say "http://www.google.com" ( Candidate can use any API of inbuilt APIs in Java like URLConnection ).
Print on console the HTML from the URL above and save it to a file ( web-content.txt) in local machine.
Write JUnit test cases for the above program.
I've successfully achieved first steps but when I am running JUnit Test Case its showing Failure.
ReadFile.java
package com.test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ReadFile
{
static void display(String input,OutputStream fos)
{
try
{
URL url = new URL(input);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
Reader reader = new InputStreamReader(stream);
int data=0;
while((data=reader.read())!=-1)
{
System.out.print((char)data);
fos.write((char)data);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input =null;
FileOutputStream fos =null;
System.out.println("Please enter any url");
try
{
input = reader.readLine();
fos = new FileOutputStream("src/web-context.txt");
display(input,fos);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
ReadFileTest.java
package com.test;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import org.junit.Test;
public class ReadFileTest {
#Test
public void test() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ReadFile.display("http://google.co.in", baos);
assertTrue(baos.toString().contains("http://google.co.in"));
}
}
I am getting following error while running JUnit Test in Eclipse:
java.lang.AssertionError
java.lang.AssertionError at org.junit.Assert.fail(Assert.java:86) at org.junit.Assert.assertTrue(Assert.java:41) at org.junit.Assert.assertTrue(Assert.java:52) at com.test.ReadFileTest.test(ReadFileTest.java:15) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown
I want that the JUnit Test Case will return true.
What's not working here is :
assertTrue(baos.toString().contains("http://google.co.in"));
and what would work is
assertTrue(baos.toString().contains("google.co.in")); // note the difference
Make something like that:
static String display(String input) {
try {
URL url = new URL(input);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
Reader reader = new InputStreamReader(stream);
int data = 0;
StringBuilder builder = new StringBuilder();
while ((data = reader.read()) != -1) {
builder.append((char) data);
}
return builder.toString();
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
I don't know why you use ByteArrayOutputStream
And now for your test case:
#Test
public void test() {
String data = ReadFile.display("http://google.co.in");
assertTrue(data != null);
assertTrue(data.contains("http://google.co.in"));
}
When I type this following URL into my browser, Bugzilla answers with XML:
http://bugzilla.mycompany.local/buglist.cgi?ctype=rdf&bug_status=CONFIRMED&product=MyProduct
I want to process this XML in a Java program. But when I use the exact same URL in my Java program, Bugzilla answers with HTML instead of XML.
This is my program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Test {
public static void main(String[] args)
throws IOException {
URL url = new URL("http://bugzilla.mycompany.local/buglist.cgi?ctype=rdf&bug_status=CONFIRMED&product=MyProduct");
URLConnection connection = url.openConnection();
final StringBuilder response = new StringBuilder(1024);
try(InputStreamReader isr = new InputStreamReader(connection.getInputStream())) {
try(BufferedReader reader = new BufferedReader(isr)) {
String inputLine = null;
while((inputLine = reader.readLine()) != null) {
response.append(inputLine);
response.append('\n');
}
}
}
System.out.println(response);
}
}
What am I doing wrong?
The resulting HTML is not the result of the query. It's Bugzillas log-in form. Duh!