Using JsonReader to read json url - java

I'm trying to read json url using JsonReader!. Once I call reader.beginArray(), I get:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING.
This is the json url :
http://www.metlink.org.nz/stop/nearbystopdata?lat=-41.278407655948&lng=174.77938892631
#Override
protected String doInBackground(String... urls) {
String result = "";
String url="http://www.metlink.org.nz/stop/nearbystopdata?lat=-41.278407655948&lng=174.77938892631";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpResponse response = httpclient.execute(httppost);
InputStream in=response.getEntity().getContent();
JsonReader reader ;
reader= new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.setLenient(true);
try {
listData=(ArrayList<DivanData>) readMessagesArray(reader);
}
finally {
reader.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public ArrayList<DivanData> readMessagesArray(JsonReader reader) throws IOException {
ArrayList<DivanData> messages = new ArrayList();
try {
reader.beginArray();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (reader.hasNext()) {
messages.add(readMessage(reader));
}
reader.endArray();
return messages;
}
What am I doing wrong?

Since you have html with content why not try to fetch json as a string from the html using jsoup (http://jsoup.org/). It's really simple and requires less code:
Document d;
String url="your_url";
d = Jsoup.connect(url).get();
Element p = d.select("body p").first(); // fetch from p tag content
String jsonString = p.text();

Related

Getting partial Json response

I am getting a server side json response to load my menu, I tried twice and it gave this error message (the Error parsing data org.json.JSONException).
the reason for that is I'm getting the response partially, in both attempts i got different responses as shown in the images. i think I'm not getting the complete json response, getting only partial response. what should I do to get the complete response.
this is my code
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
try {
path = "http://xxxxxxxxxxxxxxxxxxx";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("CetegoryCode"), "P");
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
this is the image
If your response is returning JsonArray thn need to set tht response string jsonarray. create instance of jsonarray and fill it up with the response.
if its normal get ws thn you can append parameters in url like query string
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
try {
// Append parameters with values eg ?CetegoryCode=p
String path = "http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p";
URL url = new URL(path);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
Content = sb.toString();
JSONArray jArray = new JSONArray(Content);
if (jArray != null)
Log.e("Data", "" + jArray.length());
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
}
catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
Try out below code to parse and get JSON response:
public static JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
json = convertStreamToString(stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
Use getJSONFromUrl method as below in your code:
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
try {
responseJson = new JSONObject(response);
responseJson =getJSONFromUrl("http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p");
}catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}

how to post json objects to webservices like url

I want to pass JSON objects to web services like this
firstname=jhon&lastname=mic&mail=jhon#gmail.com&sex=M&hometown=blablabla
how can I pass,any one please help me.Am trying like this
JSONObject json = new JSONObject();
json.put("firstname", firstname);
json.put("lastname", laststname);
json.put("mail", mail);
json.put("sex", sex);
json.put("hometown", hometown)
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
post.setEntity(new ByteArrayEntity(json1.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null)
{
InputStream instream=entity.getContent();
String result=convertStreamToString(instream);
}
public static String convertStreamToString(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();
}
But this code not posted the right value to webservice,Is there any wrong please help me ,
Thank you:)
StringBuilder bu = new StringBuilder();
for(int i = 0; i<json.names().length(); i++){
bu.append("&");
try {
bu.append(json.names().getString(i)+"="+json.get(json.names().getString(i)));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bu.toString();//give you parameters

ClascastException in linking JavaConnector in kony

I have created a simple java service in kony app.When i try to run the Test with input parameter i got the following exception.
java.lang.ClassCastException: com.kony.sample.KonyServerConnection cannot be cast to com.konylabs.middleware.common.JavaService
at com.konylabs.middleware.connectors.JavaConnector.execute(JavaConnector.java:142)
at com.pat.tool.keditor.editors.JavaServiceDefinitionEditorPage.getJavaResponse(JavaServiceDefinitionEditorPage.java:1878)
at com.pat.tool.keditor.editors.JavaServiceDefinitionEditorPage$InvokeJavaOperation.run(JavaServiceDefinitionEditorPage.java:1842)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
i followed this Link for reference
i have shared some of java code
private static final String URL = "http://serverurl/sendEmail?";
public static String getServerPersponce(String entitiy,String mHeader){
String responseBody = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
System.out.println("Requesting : " + httppost.getURI());
try {
StringEntity entity = new StringEntity(entitiy);
if(mHeader != null && !mHeader.equalsIgnoreCase(""))
httppost.addHeader("AuthToken" , mHeader);
httppost.setEntity(entity);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
InputStream stream = entity1.getContent();
responseBody = getStringFromInputStream(stream);
if (response.getStatusLine().getStatusCode() != 200) {
// responseBody will have the error response
}
//responseBody = httpclient.execute(httppost, responseHandler);
System.out.println("responseBody : " + responseBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return responseBody;
}
public static void main(String[] args) throws Exception {
String data = "{\"CC\":[\"yuvarajag#gmail.com\"],\"Content\":\"sample string 2\",\"Subject\": \"sample string 1\",\"To\": [\"yuvarajag#gmail.com\",\"sakumarr#gmail.com\",]}";
String result = getServerPersponce(data, accessToken);
System.out.println("Result "+result);
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString().trim();
}
This java code is working fine. after creating a jar i included this jar to the Kony app.I am getting exception in kony java service integration.
In the code specified there is no implementation of com.konylabs.middleware.common.JavaService2 class. JavaService will work if you implement JavaService2 class in your class file and override its invoke meathod.
below is the sample:
public class <YOUR CLASS NAME> implements JavaService2 {
#Override
public Object invoke(String serviceId, Object[] arg1,
DataControllerRequest arg2, DataControllerResponse arg3)
throws Exception {
// YOUR LOGIC
return result;
}
}
Kony JavaConnector expects classes that implements JavaServer or JavaService2. Apparently com.kony.sample.KonyServerConnection does not implements them.

How do I display a Java HttpPost object as a string?

I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.
How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?
Should use it after execute
public static String httpPostToString(HttpPost httppost) {
StringBuilder sb = new StringBuilder();
sb.append("\nRequestLine:");
sb.append(httppost.getRequestLine().toString());
int i = 0;
for(Header header : httppost.getAllHeaders()){
if(i == 0){
sb.append("\nHeader:");
}
i++;
for(HeaderElement element : header.getElements()){
for(NameValuePair nvp :element.getParameters()){
sb.append(nvp.getName());
sb.append("=");
sb.append(nvp.getValue());
sb.append(";");
}
}
}
HttpEntity entity = httppost.getEntity();
String content = "";
if(entity != null){
try {
content = IOUtils.toString(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("\nContent:");
sb.append(content);
return sb.toString();
}
snippet
I usually do post in this way (The server answer is a JSON object) :
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
And postData is:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
#SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Hope it helps
Well i actually did HTTP-Post using NameValuePair...... I am showing the code which i use to do an HTTP-Post and then converting the Response into a String
See the below Method code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

When trying to get Xml data from URL, it returns null

I'm trying to get xml data and parse it with an async task. Here is what I did :
In OnCreate method I get url as string. I tested my url and it doesn't return null. Also has permission to connect to Internet.
startDownload start = new startDownload();
start.execute(url.toString());
And my Async class :
protected class startDownload extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
eczaDialog = ProgressDialog.show(ListViewXML.this,"", "Loading...");
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize(); ....
When i debug my code i saw that this doc variable returned null. I don't understand where was the problem. I hope you can help me to find out Thanks.
You have to get the content of the xml. You can use this, the code returns the content in the string, after you can create an XML object :
public static String getStringPage(String url){
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = null;
HttpClient httpClient = null;
HttpGet httpGet = null;
URI uri = null;
HttpResponse httpResponse = null;
InputStream inputStream = null;
String HTMLCode = null;
//Create client and a query to get the page
httpClient = new DefaultHttpClient();
httpGet = new HttpGet();
//Set the query with the url in parameter
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
httpGet.setURI(uri);
//Execute the query
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Create a buffer to get the page
try {
inputStream = httpResponse.getEntity().getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Get the buffer caracters
try {
HTMLCode = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (HTMLCode!= null){
stringBuffer.append(HTMLCode);
stringBuffer.append("\n");
try {
HTMLCode = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
//Return the string of the page code
return stringBuffer.toString();
}

Categories

Resources