As the title says ... I have tried to use the following code to execute a PHP script when user clicks a button in my Java Swing application :
URL url = new URL( "http://www.mywebsite.com/my_script.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
But nothing happens ... Is there something wrong ?
I think you're missing the next step which is something like:
InputStream is = conn.getInputStream();
HttpURLConnection basically only opens the socket on connect in order to do something you need to do something like calling getInputStream() or better still getResponseCode()
URL url = new URL( "http://google.com/" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
// do something with the data here
}else{
InputStream err = conn.getErrorStream();
// err may have useful information.. but could be null see javadocs for more information
}
final URL url = new URL("http://domain.com/script.php");
final InputStream inputStream = new InputStreamReader(url);
final BufferedReader reader = new BufferedReader(inputStream).openStream();
String line, response = "";
while ((line = reader.readLine()) != null)
{
response = response + "\r" + line;
}
reader.close();
"response" will hold the text of the page. You may want to play around with the carriage return (depending on the OS, try \n, \r, or a combination of both).
Hope this helps.
Related
I wrote a program where I call many http get request. It takes like half a minute till all the get requests are done but it needs to be done within a second, this can be achieved with calling this method asynchronously, right? But how?
This is what my get request looks like:
public static String dataRequest(String link) throws IOException {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String output;
String result = "";
while ((output = br.readLine()) != null) {
result += output;
}
conn.disconnect();
return result;
}
I tried using RxJava but I couldn't get it to work at all. I'm in a Maven JavaFx project. This method is in my getData class.
You can try using thread with ForkJoinPool
For example -> https://www.baeldung.com/java-fork-join
I want to get a json string from my remote server.
I have a very weird problem as I manage to get my json string only thanks to getErrorStream but not thanks to getInputStream.
Here is my code:
URL url = new URL("my_https_url");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseStatusCode = connection.getResponseCode(); // ERROR 500 HERE
InputStream inputStream;
if(responseStatusCode != HttpsURLConnection.HTTP_OK ) {
inputStream = connection.getErrorStream(); // I pass through here
} else {
inputStream = connection.getInputStream();
}
response = IoUtils.readAll(inputStream); // I get my json string properly after being passed through getErrorStream()
If I remove my 'if statement' and try to do only:
inputStream = connection.getInputStream()
I get a fileNotFoundException.
Anybody has a clue how to solve this issue?
Thanks.
I want to get a query result from Stack Exchange API using my Java program. For example, I want to pass this URL and get the data of the question with id 805107. I have tried but only got the resulted web page content. I did not get the query result, i.e. the question data, although the resulted page shows the question data.
url = new URL ("https://api.stackexchange.com/docs/questions-by-ids#order=desc&sort=activity&ids=805107&filter=default&site=stackoverflow&run=true");
byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
String encoding = new String (encodedBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput (true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
connection.connect();
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
As Stephen C said, you need to use the query URL, not the URL of the documentation. You can find the query URL in the "Try it" part of the documentation page. Try using
url = new URL ("https://api.stackexchange.com/2.2/questions/805107?order=desc&sort=activity&site=stackoverflow")
It will return the result you are looking for as JSON like it is displayed on the documentation page.
I am trying to get data from an MySQL database using a php-file. My java code is as follows:
HttpURLConnection conn = null;
URL url = null;
try {
url = new URL(getURL);
System.out.println(getURL);
conn = (HttpURLConnection)url.openConnection();
//conn.setReadTimeout(READ_TIMEOUT);
//conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("user", USER);
builder.appendQueryParameter("pass", PASS);
builder.appendQueryParameter("server", SERVER);
builder.appendQueryParameter("db", DB);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
result = reader.readLine();
return(result);
}else{
return("unsuccessful");
}
When I go to my url (hidden in the variable getURL) using a browser, I see string of json on my screen, just as it should. However, when I output the contents of the reader (above code only takes the first line, but by adapting the code I can, of course, output more) it shows the html-code for a website displaying a 404 - Page does not exist message.
Anyone has any idea what goes wrong? Yes, I did check for typo's.
Okay, I have no clue what happened, as I didn't change anything. But all of the sudden it started working?!?
Must have been something server-side I guess...
Thanks for the input and sharing your thoughts!
I am tiring to execute some of my project URLs through JAVA APIs. But some of them contain JSON values. Its not accepting the JSON I am providing.
If I hit same URL through browser it executes. I am not getting what is going wrong. Are the " " specified not accepted ?
URL = http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
The Code is as follows
String requestString = "http://admin.biin.net:8289 /project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE"
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer responseString = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
Error :
java.io.IOException: Server returned HTTP response code: 505 for URL: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
If I remove the JSON the URL executes.
Don't pass json in QueryString. Since you are using HTTP POST. You should send the sensitive data in the HTTP body. Like this
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
For your current problem. Encode the json value before passing it in url.
Try this:
try {
String s = "http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON="
+ URLEncoder.encode("{\"fieldIds\":[{\"id\":1360,\"value\":\"project SS33\"},{\"id\":1362,\"value\":\"12/03/2015\"},{\"id\":1363,\"value\":\"12/31/2015\"}],\"state\":1}", "UTF-8")
+ "&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE";
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Result: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON=%7B%22fieldIds%22%3A%5B%7B%22id%22%3A1360%2C%22value%22%3A%22project+SS33%22%7D%2C%7B%22id%22%3A1362%2C%22value%22%3A%2212%2F03%2F2015%22%7D%2C%7B%22id%22%3A1363%2C%22value%22%3A%2212%2F31%2F2015%22%7D%5D%2C%22state%22%3A1%7D&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE