java and php get request - java

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.

Related

URL PARAMETER - JAVA

I am doing an desktop application using Java that can send SMS to a multiple phone numbers via browser. To send the SMS, I need to put in parameters that username, password, message to be sent and the recipient's number.
I have used this and it worked but the problem is it opens up a browser to every recipient so it is not advisable especially if its going to be sent to a lot:
Runtime rt = Runtime.getRuntime();
String url = String.format("http://www.companysms.com/RemoteAPI/SendSMS.aspx?username=%s&encoding=url&password=%s&messagedata=%s&receiver=%s&binary=0", txtUsername.getText(),txtPassword.getText(), txtMessage.getText(),tblMessage.getValueAt(i, 2));
rt.exec("rundll32 url.dll,FileProtocolHandler "+ url);
I have tried this one too but it gives me the HTTP response code 400:
HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder results = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
results.append(line);
}
connection.disconnect();
If I use the URLencoder with "UTF-8", it makes it worse because i cant be sure of what the message the user will send and if they will use any of the special characters. Is there a way to have the first set of codes that I used to not open browser after sending the SMS or is there another way of doing this? Any help is appreciated. Thanks!

How to move from URL to URL in Java (Re-use reader-object?)

Sorry for the very basic question, I am new to Java.
To get data from an URL I use code like this
URL url = new URL(BaseURL+"login?name=foo");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
while ((inputLine = in.readLine()) != null)
...
That works perfectly fine. When I now want to continue and send the next command to the server (like ".../getStatus"), do I need to create these objects over and over again, or is there a smarter way?
Thanks!
You have to call openConnection again in order to get a new URLConnection. The HttpURLConnection does internal caching, though, so if the HTTP-server supports Connection: keep-alive the underlying connection to the server will be reused so it's not that bad as it originally might look. It's just hidden from you.
I looked into the Apache HttpComponents (HttpClient) and it still requires a lot of code. As I don't need cookie-handling (it's only a simple RESTful server giving json-blocks as responses) I'm going for a very simple solution:
public static String readStringFromURL(String requestURL) throws IOException
{
URL u = new URL(requestURL);
try (InputStream in = u.openStream()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
For me that looks like a perfect solution, but as mentioned, I am new to Java and open (and thankful) for hints...

HTML Form Action Java

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

Creating a view in Struts2 to get a view of another application through URL

I need to make a struts 2 application. In the one view of this app, I have to get the view of another application through the URL provided for example (http://localhost:8080/hudson/)...
Now.
1. How to connect with the other application? (Can it be done with Apache HttpURLClient? OR any other way please guide. )
2 .If it can be done with Apache HttpURLClient, then how to render the Response object in stuts2 framework.
Please help. Many thanks in advance.
You can use java.net package to resolve the issue. Example Code :
URL urlApi = new URL(requestUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlApi.openConnection();
httpURLConnection.setRequestMethod(<requestMethod>); // GET or POST
httpURLConnection.setDoOutput(true);
//in case HTTP POST method un-comment following to write request body
//DataOutputStream ds = new DataOutputStream(httpURLConnection.getOutputStream());
//ds.writeBytes(body);
InputStream content = (InputStream) httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(content));
StringBuilder stringBuilder = new StringBuilder(100);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String serverResult = stringBuilder.toString();
//now you have a string representation of the server result page
//do what you need
Hope this helps
I have to do the same, i`m using struts2 but i have doing a servlet. In struts.xml you have to put you can get the content of the url with httpauarlconnection or with httpclient (apache) and and put it at servlet response.
I have this but i have problems with the relative links of the html because it try to resolve with my domain name (the name of the servlet that make the work).

Servlet that sends back JSON: Confusion on reception

I have a Servlet that sends back a JSON Object and I would like to use this servlet in another Java project. I have this method that gets me the results:
public JSONArray getSQL(String aServletURL)
{
JSONArray toReturn = null;
String returnString = "";
try
{
URL myUrl = new URL(aServletURL);
URLConnection conn = myUrl.openConnection();
conn.setDoOutput(true);
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
String s;
while ((s = in.readLine()) != null )
returnString += s;
in.close();
toReturn = new JSONArray(returnString);
}
catch(Exception e)
{
return new JSONArray();
}
return toReturn;
}
This works pretty will, but the problem I am facing is the following:
When I do several simultaneous requests, the results get mixed up and I sometimes get a Response that does not match the request I send.
I suspect the problem to be related to the way I get the response back: The Reader reading a String from the InputStream of the connection.
How can I make sure that I get one reques -> one corresponding reply ?
Is there a better way to retrieve my JSON object from my servlet ?
Cheers,
Tim
When I do several simultaneous requests, the results get mixed up and I sometimes get a Response that does not match the request I send.
Your servlet is not thread safe. I'd bet that you've improperly assigned request scoped data either directly or indirectly as instance or class variables of the servlet. This is a common beginner's mistake.
Carefully read this How do servlets work? Instantiation, sessions, shared variables and multithreading and fix your servlet code accordingly. The problem is not in the URLConnection code shown so far, although it indicates that you're doing exactly the same job in both doGet() and doPost(), which in turn is already a smell as to how the servlet is designed.
Try removing setDoOutput(true), you are using the connection only for input and so you shouldn't use it.
Edit: alternatively try using HttpClient, it's much nicer that using "raw" Java.

Categories