I have a java program which I want to input something into an html form. If possible it could just load a url like this
.../html_form_action.asp?kill=Kill+Server
But i'm not sure how to load a url in Java. How would I do this? Or is there a better way to send an action to an html form?
Depending on your security, you can make an HTTP call in Java. It is often referred to as a RESTFul call. The HttpURLConnection class offers encapsulation for basic GET/POST requests. There is also an HttpClient from Apache.
Here's how you can use URLConnection to send a simple HTTP request.
URL url = new URL(url + "?" + query);
// set connection properties
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.connect(); // send request
// read response
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close(); // close connection
Related
when you open a connection via URLConnection to read the content of a Webpage,
try {
URL url = new URL("https://stackoverflow.com/questions/46939965/does-java-urlconnection-send-metadata");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection;
connection = (HttpURLConnection) urlConnection;
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String current;
while((current = in.readLine()) != null) {
urlString += current;
}
}catch(IOException e) {
e.printStackTrace();
}
what will Java leave for Information?
Will statistical data like the Webbrowser saved? Will that be the "Java"?
Thx for help,
~Corn
HTTP "metadata" is normally sent in the headers. The one that would indicate the web browser is typically called "USER_AGENT." I do not believe Java will populate these headers for you implicitly.
i want to make an application which is based on a php page, sending to it parameters to obtain data from the remote db through the php page.
I will use jsons, but my question is:
assumed i use this code to send request:
URL url = new URL("http://www.francescorizzi.altervista.org/Main.php?Request=Login&UserName=mario&Password=lol");
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
Should i recreate the url object, conn, and rd at each new request? or is there a more efficient way to do this?
Please note: I'm new to http handling through java.
since it is an http request and you retrieving data from that particular url, there is a need to recreate the object because the site may get updated later. so creating new object again will dispose the previous object reference and also close connection after retrieving data.
I am trying to hit the URL and get the response from my Java code.
I am using URLConnection to get this response. And writing this response in html file.
When opening this html in browser after executing the java class, I am getting only google home page and not with the results.
Whats wrong with my code, my code here,
FileWriter fWriter = null;
BufferedWriter writer = null;
URL url = new URL("https://www.google.co.in/?gfe_rd=cr&ei=aS-BVpPGDOiK8Qea4aKIAw&gws_rd=ssl#q=google+post+request+from+java");
byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
String encoding = new String(encodedBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.connect();
InputStream content = (InputStream) connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
try {
fWriter = new FileWriter(new File("f:\\fileName.html"));
writer = new BufferedWriter(fWriter);
while ((line = in.readLine()) != null) {
String s = line.toString();
writer.write(s);
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Same code works couple of days back, but not now.
The reason is that this url does not return search results it self. You have to understand google's working process to understand it. Open this url in your browser and view its source. You will only see lots of javascript there.
Actually, in a short summary, google uses Ajax requests to process search queries.
To perform required task you either have to use a headless browser (the hard way) which can execute javascript/ajax OR better use google search api as directed by anand.
This method of searching is not advised is supposed to fail, you must use google search APIs for this kind of work.
Note: Google uses some redirection and uses token, so even if you will find a clever way to handle it, it is ought to fail in long run.
Edit:
This is a sample of how using Google search APIs you can get your work done in reliable way; please do refer to the source for more information.
public static void main(String[] args) throws Exception {
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search = "stackoverflow";
String charset = "UTF-8";
URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
// Show title and URL of 1st result.
System.out.println(results.getResponseData().getResults().get(0).getTitle());
System.out.println(results.getResponseData().getResults().get(0).getUrl());
}
I want to do an online xml request in java but the server responds with 401 error that means that there is an authentication that is need to access the server. I have the certfile.cer that i can use to do the authentication but i dont know how to load it in java.How can I achieve this in java? Here is part of my code.
StringBuilder answer = new StringBuilder();
URL url = new URL("www.myurl.com");
URLConnection conn = url.openConnection();
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xml);
writer.flush();
String line;
while ((line = reader.readLine()) != null)
{
answer.append(line);
}
I have to send an HTTP request to our C programme which is running on a Linux machine. How can I send an HTTP request in Java to our server which is in C and running on a Linux machine?
public void sendPostRequest() {
//Build parameter string
String data = "width=50&height=100";
try {
// Send the request
URL url = new URL("http://www.somesite.com");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//write parameters
writer.write(data);
writer.flush();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
//Output the response
System.out.println(answer.toString());
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
The above example is for sending a POST request using a URL.
If you're asking how to send an HTTP request in Java to a web server written in C, you can use the URLConnection class.
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close(); } catch (Exception e) { }
The above example is for sending a POST request using a URL.
Also take a look at Sun Tutorial on reading/Writing from/to a URLConnection. The other option is to use Apache HTTPComponents which has examples for the HttpCore and HttpClient module.
If you are looking into implementing the web Server, you will have to handle the Http request yourselves which involves a thread pool, parsing the requests, generating HTML, security, multiple sessions, etc or follow the easy route by using off-the-shelf web server like Apache and seeing which all high-level languages like Perl, Ruby can be used for developing the web application.
For implementing your own Http server, please take a look at Micro-Httpd or tinyHttpd
You may also want to look at Adding Web Interface -C++ application which has a sample code.
From the way your question is worded.. I think you need to know some basic stuff before you can start. Try try googling for a simple guide to how web servers work.
Once you have the basic idea, there are a couple of options for a C programmer:
1) You want your C program to be running continuously, waiting for a request from your Java.
In this case, you will have to code your C program to open a Socket and Listen for connections. See http://www.linuxhowtos.org/C_C++/socket.htm for example.
OR
2) You have a web Server on your server which will run your C program each time a particular request is made? In this case, you will have to code your C as a CGI program. See http://www.cs.tut.fi/~jkorpela/forms/cgic.html for example.
Hint: (2) is much easier!