sending parameters across applications - java

Is there a way I can send attributes across applications that may or may not be on the same machine ?
For example :
// IN APPLICATION 1 (APP-1)
request.setAttribute("Truth","Ghazal is the food for the soul of separation");
RequestDispatcher rd = request.getRequestDispatcher("http://IP/App-2/servlet");
rd.forward(request,response);
// IN APPLICATION 2'S (APP-2) SERVLET
String truth = request.getAttribute("Truth").toString();
// NOW USE THIS STRING
Let us suppose that IP on which app-1 is deployed is not the same as the IP on which the app-2 is deployed.
Is there any way I can send parameters like these across applications that are hosted far away from each other ? When I tried I couldn't do this way,but may be there is a way around.
Both the applications use Tomcat.

If you are going to be sharing state between a variable number of machines, then using HTTP as the method to store that state is not very reliable.
"Attributes" are not transmitted over HTTP, they are merely shared state that reside on the application for the given session. Attributes are 100% purely server-side information.
From the Javadocs:
"It is warned that when the request is dispatched from the servlet
resides in a different web application by RequestDispatcher, the
object set by this method may not be correctly retrieved in the caller
servlet."

you can create a base package to be used through the application
package base;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetXMLTask
{
static double longitute;
static double latitude;
public ArrayList<JSONObject> getOutputFromUrl1(String url)
{
ArrayList<JSONObject> output = new ArrayList<JSONObject>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
StringBuilder builder= new StringBuilder();
JSONObject myjson ;
JSONArray the_json_array;
try
{
response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
char[] buf = new char[8000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = in.read(buf);
}
myjson = new JSONObject("{child:"+builder.toString()+"}");
JSONObject mmm = new JSONObject(builder.toString());
JSONArray mmmArr = mmm.getJSONArray("status");
the_json_array = myjson.getJSONArray("child");
for (int i = 0; i < the_json_array.length(); i++)
{
JSONObject another_json_object = the_json_array.getJSONObject(i);
output.add(another_json_object);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return output;
}
}
now from your application call this method by
ArrayList<JSONObject> obj = new GetXMLTask().getOutputFromUrl1("url for the other application method which responds");

Related

Is possible to call servlet from applet

I am not familiar with java and applets, so any one please let me know the possibilities for the following my questing.
I would like to call the Servlet from applet.. is this possible?
If the 1st one is possible can we store the Servlet output like XML data or string in the applet variable?
If the 2nd one is possible, then can get that that variable value using JavaScript or J Query?
If possible please give me the simple example.
Thanks in advance.
Yes you can. The servlet exposes a URL, which you can get with the help of the URLConnection class.
Again you can do this, see here on how you can use the URL connection.
You can do that too, create an applet to get the applet field, and look here on how you can invoke the method.
But all these sound awfully complicated. Why don't you tell us what you are trying to achieve, maybe there is a simpler way to do things.
One : yes you can call the servlet from applet making http calls
step 1 : make a http call to your servlet
step 2 : make your servlet return XML response
step 3 : parse xml response
using this program you can make a call to your servlet
package com.hussain;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class callServlet {
public static void main(String[] args)
{
String servletResponse = callServlet.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb");
callServlet.parseFromXMLResponse(servletResponse);
}
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void parseFromXMLResponse(String respo)
{
// parse your XML response here
}
}
Moving in the flow of your question,
You may call the servlet from your applet:
Construct the url that will hit your servlet.
Use java.net.URLConnection object to hold the connection from your appletURLConnection con = urlToServlet.openConnection()
'con.setDoOutput(true)' => Application intends to write data to the URL connection.
Use the input and output streams to communicate with the Servlet.
con.getInputStream() and con.getOutputStream()
[Note: Don't forget to close all the connections and streams]
Now, use the data you obtained from the InputStream, in what so ever form you want.
Its extreamly simple, use this code:
In Applet:
public String getYourString(){ return responseFromServlet;}
In Javascript:
var jsResp = document.name_of_your_applet.getYourString();
Hope, you've got your answers!

execute a jsp program on background of a running java program

I just want execute my jsp program when a button on my running java program is clicked, it doesn't need to be visible, the jsp program i am saying is for printing and once it is loaded in the browser it will just pop up the print dialog confirm box, so again it doesn't need to be visible, once the button in my java program is clicked the print dialog will just pop up and that's it. By the way i am new here in this site, and also know only basics of java, so i do not have any idea how to do it, but i like to do it that way and with just a link of the jsp page from the localhost, something like that,
Thanks in advance buddies! Hope you will help me!...
this should be working , cant be sure if it serves properly , please assure me the outcome
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class callURL {
public static void main(String[] args)
{
String url = "http://localhost:8080/OpenID/asd.html";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
StringBuilder builder= new StringBuilder();
try
{
response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
char[] buf = new char[8000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = in.read(buf);
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
for this java program to ececute your jsp
you have to add this line in your jsp page
<script>
window.location.href="http://localhost:8080/OpenID/asd.html"
</script>
where OpenId : Application Name
asd.html is your jsp page , the same jsp which you are calling from java program

How to consume REST in Java [duplicate]

This question already has answers here:
How do you create a REST client for Java? [closed]
(18 answers)
Closed 2 years ago.
Using Java tools,
wscompile for RPC
wsimport for Document
etc..
I can use WSDL to generate the stub and Classes required to hit the SOAP Web Service.
But I have no idea how I can do the same in REST.
How can I get the Java classes required for hitting the REST Web Service.
What is the way to hit the service anyway?
Can anyone show me the way?
Working example, try this:
package restclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:3002/RestWebserviceDemo/rest/json/product/dynamicData?size=5");//your url i.e fetch data from .
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;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
}
}
As others have said, you can do it using the lower level HTTP API, or you can use the higher level JAXRS APIs to consume a service as JSON. For example:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://host:8080/context/rest/method");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);
Its just a 2 line of code.
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
YourBean obj = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", YourBean.class);
Ref. Spring.io consuming-rest
The code below will help to consume rest api via Java.
URL - end point rest
If you dont need any authentication you dont need to write the authStringEnd variable
The method will return a JsonObject with your response
public JSONObject getAllTypes() throws JSONException, IOException {
String url = "/api/atlas/types";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host + url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header("Authorization", "Basic " + authStringEnc);
Response response = invocationBuilder.get();
String output = response.readEntity(String.class
);
System.out.println(response.toString());
JSONObject obj = new JSONObject(output);
return obj;
}
Just make an http request to the required URL with correct query string, or request body.
For example you could use java.net.HttpURLConnection and then consume via connection.getInputStream(), and then covnert to your objects.
In spring there is a restTemplate that makes it all a bit easier.
If you also need to convert that xml string that comes as a response to the service call, an x object you need can do it as follows:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class RestServiceClient {
// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) throws ParserConfigurationException,
SAXException {
try {
URL url = new URL(
"http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
Ciudades ciudades = new Ciudades();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println("12132312");
System.err.println(output);
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));
Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
.getElementsByTagName("ciudad");
for (int i = 0; i < nodes.getLength(); i++) {
Ciudad ciudad = new Ciudad();
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("idCiudad");
Element element2 = (Element) name.item(0);
ciudad.setIdCiudad(Integer
.valueOf(getCharacterDataFromElement(element2)));
NodeList title = element.getElementsByTagName("nomCiudad");
element2 = (Element) title.item(0);
ciudad.setNombre(getCharacterDataFromElement(element2));
ciudades.getPartnerAccount().add(ciudad);
}
}
for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
Note that the xml structure that I expected in the example was as follows:
<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>
Look at Jersey. Again, REST is all about the data. And a tutorial here
JAX-RS but you can also use regular DOM that comes with standard Java
From your question its not clear whether you are using any frameworks.For REST you will be getting an WADL & Apache CXF recently added support for WADL-first development of REST services.Please go through http://cxf.apache.org/docs/index.html
You can able to consume a Restful Web service in Spring using RestTemplate.class.
Example :
public class Application {
public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> call= restTemplate.getForEntity("http://localhost:8080/SpringExample/hello",String.class);
System.out.println(call.getBody())
}
}
Reference
Apache Http Client APIs are very commonly used for calling HTTP Rest services.
Here is one of example of consuming HTTP GET call.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
public class CallHTTPGetService {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest httpUriRequest = new HttpGet("URL");
HttpResponse response = client.execute(httpUriRequest);
System.out.println(response);
}
}
Use following maven dependency if using Maven project.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.1</version>
</dependency>

Cannot retrieve data from MySQL table which matches specific "uid"

I am trying to learn more about MySQL and using Java (on Android) to access and retrieve information from a database on my WAMS server. The way my app is setup is that it has an initial login screen which also grabs the "uid" of the username that's logging in (from a different table) and stores it.
Upon login (which is functional - I setup a toast notification that displays the retrieved username and uid of the user logging in), it goes to a new screen (dashboard.xml) which has a TextView field setup to display the retrieved data (from table posted below) associated with the stored "uid". Here is the table I am trying to pull data from:
http://db.tt/4izVQuGB
Now, I have setup a PHP file that queries my db for rows that are associated with a specific "uid". I have tested this file using an HTML form.
$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
mysql_select_db($dbdb)or die("database selection error");
//Retrieve the User ID
$uid = $_POST['uid'];
//Query
$query = mysql_query("SELECT * FROM node WHERE uid='$uid' AND type='goal'");
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
while($results=mysql_fetch_assoc($query)) {
//Store the returned data into a variable
$output = $results;
//encode the returned data in JSON format
echo json_encode($output);
}
mysql_close();
}
The result I get by testing the PHP file using uid value of 1 is:
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the
hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
Now, I have written some android code which sets up httppost and is supposed to retrieve the "titles" in my database table. I know it is wrong (obviously since it doesn't work) but I am confused as to what to do next.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Dashboard extends Activity implements OnClickListener {
// variable declarations
String uid = "1";
// create textview to display retrieved data
TextView display;
HttpClient httpclient;
HttpPost httppost;
HttpResponse httpresponse;
HttpEntity httpentity;
ArrayList<NameValuePair> resultArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
display = (TextView) findViewById(R.id.test);
// initialize HttpClient
httpclient = new DefaultHttpClient();
// initialize HttpPost
httppost = new HttpPost("http://192.168.1.112/android/fetch.php");
try {
// Create new List
List<NameValuePair> resultList = new ArrayList<NameValuePair>();
resultList.add(new BasicNameValuePair("uid", uid));
httppost.setEntity(new UrlEncodedFormEntity(resultList));
httpresponse = httpclient.execute(httppost);
httpentity = httpresponse.getEntity();
InputStream instream = entity.getContent();
try {
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
JSONObject jData = null;
for (int i = 0; i < jArray.length(); i++) {
jData = jArray.getJSONObject(i);
String goals = jData.getString("title");
display.setText(goals);
}
//} catch (JSONException e) {
//Toast.makeText(this, "No entries found", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
e.printStackTrace();
Notifications error = new Notifications();
error.userPassErrorDialog();
}
}
private static String streamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I get the following error when testing it in the Android emulator:
http://db.tt/2vg9MqYh
Any help or suggestions will be greatly appreciated.
In your Android app, you expect a JSONArray:
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
However, in your PHP file you only output multiple separate JSON objects instead of a real array. I think, you should collect all items from the database in an PHP array first and then encode and output it only once.
My PHP skills are a bit rusted, but I hope this one will work:
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
$output = array();
while($results = mysql_fetch_assoc($query)) {
// append row to output
$output[] = results
}
mysql_close(); // shouldn't that be outside the if block?
//encode the returned data in JSON format
echo json_encode($output);
}
I would expect the output then to be like this (maybe without indentation):
[
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
]
The problem lies in encoding and decoding of JSON. from your JSON response it looks like you are receiving JSON object from server also please try to validate you JSON response here. run your php file in browser, copy the entire response on the JSON validator and check the brackets that you are receiving the response in.
1. If your response starts with '[' it is and array and if it starts with '{' it is a JSON Object. while parsing JSON you have defined JSON array first but the server response is JSON object. While using JSON you have to be careful on server side for the format of response it will send and you have to be careful on the client side for the format of response you receive. I am posting example script for you.
-> Server side
if (mysql_num_rows($result)>0){
$response["data"] = array(); //this is an array
while($row= mysql_fetch_array($result))
{
$data = array(); //here I have created another temp array
$data["name"] = $row["name"];
$data["surname"] = $row["surname"];
array_push($response["data"], $data); //this makes an array of objects in the response
}}
}//endif
else{
echo "no input";
}}
mysql_close();
echo json_encode($response); //and finally I echo it as an JSON object
As this php script will return me one object of array of objects ( bit complex isn't it!!) below is the format of response
-> validated JSON response
{
"data": [
{
"name": "Setu",
"surname": "Desai",
}
]
}
and to decode this my client site script need to be the following
-> parsing JSON object
JSONObject snObject = new JSONObject(jsonString);
JSONArray snArray = snObject.getJSONArray("data");
for (int i = 0; i < snArray.length(); i++) {
JSONObject snObject2 = snArray.getJSONObject(i);
String surname = snObject2.getString("surname");
surnamearray.add(surname);
}
the simple way to understand is to validate you JSON response and identify the position of JSON array and objects and then start decoding.

Automate HTML form submission using Java to find grocery hours

I'm trying to automate form submission using Java to get the hours of a grocery store here:
www.giantfood.com
I've posted the query and the hidden miles and storeType fields of the form, but my output.html is just the original web header and footer with an error message in the body. What am I doing wrong?
import java.io.*;
import java.net.*;
public class PostHTML
{
public static void main(String[] args)
{
try
{
URL url = new URL( "http://www.giantfood.com/our_stores/locator/store_search.htm" );
HttpURLConnection hConnection = (HttpURLConnection)
url.openConnection();
HttpURLConnection.setFollowRedirects( true );
hConnection.setDoOutput( true );
hConnection.setRequestMethod("POST");
PrintStream ps = new PrintStream( hConnection.getOutputStream() );
ps.print("groceryStoreAddress=20814&groceryStoreMiles=10&storeType=GROCERY");
ps.close();
hConnection.connect();
if( HttpURLConnection.HTTP_OK == hConnection.getResponseCode() )
{
InputStream is = hConnection.getInputStream();
OutputStream os = new FileOutputStream("output.html");
int data;
while((data=is.read()) != -1)
{
os.write(data);
}
is.close();
os.close();
hConnection.disconnect();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
UPDATE
Thanks! Using &'s worked. I'm trying to use HttpClient but I'm getting another error now:
package clientwithresponsehandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
/**
* This example demonstrates the use of the {#link ResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated resources.
*/
public class ClientWithResponseHandler {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpost = new HttpPost("http://www.giantfood.com/our_stores/locator/store_search.htm");
System.out.println("executing request " + httpost.getURI());
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("groceryStoreAddress", "20878"));
nvps.add(new BasicNameValuePair("groceryStoreMiles", "10"));
nvps.add(new BasicNameValuePair("storeType", "GROCERY"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
Output:
run:
executing request http://www.giantfood.com/our_stores/locator/store_search.htm
Exception in thread "main" org.apache.http.client.HttpResponseException: Moved Temporarily
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:67)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:55)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:945)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:919)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:910)
at clientwithresponsehandler.ClientWithResponseHandler.main(ClientWithResponseHandler.java:39)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
I don't understand the Moved Temporarily error.
try to use
ps.print("groceryStoreAddress=20814&groceryStoreMiles=10&storeType=GROCERY")
instead
BTW, it's easier to use some http-library, like Apache HttpClient
Solved the Moved Temporarily by learning about HTML Redirects:
Httpclient 4, error 302. How to redirect?

Categories