java url connection set cookie - java

I followed Ian Brown's tutorial to set a cookie to a request http://www.hccp.org/java-net-cookie-how-to.html
but it don't works:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class cookie {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
URL myUrl = null;
try {
myUrl = new URL("http://server/test.php?hlp");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URLConnection con = myUrl.openConnection();
con.setRequestProperty("Cookie", "accesstoken=WERT-DES-COOKIES");
con.connect();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println(builder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the php-test-Script returns the $_REQUEST-values... but I only get the "hlp"-Parameter given in the URL. Can somebody tell me whats wrong?!

You mentioned that you are using $_REQUEST to retrieve the cookies. Please note that $_REQUEST will retrieve only request parameters either passed as query string or as POST request. To retrieve cookie use $_COOKIE associative array. Check this tutorial.

Related

Parsing cookies to client side

Trying to access the cookies in my DownloadDemo class (downloads information on a website in a csv file) but can't seem to find the correct method to do so. My code:
import java.io.*;
import java.net.URL;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadDemo extends CookieTest
{
public static void main(String[] args)
{
StringBuilder contents = new StringBuilder(4096);
BufferedReader br = null;
try
{ //goes to the given URL
String downloadSite = ((args.length > 0) ? args[0] : "google.com");
// file saved in your workspace
String outputFile = ((args.length > 1) ? args[1] : "test.csv");
URL url = new URL(downloadSite);
InputStream is = url.openConnection().getInputStream();
br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(new FileOutputStream(outputFile));
String line;
String newline = System.getProperty("line.separator");
while ((line = br.readLine()) != null)
{
contents.append(line).append(newline);
}
ps.println(contents.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try { if (br != null) br.close(); } catch(IOException e) { e.printStackTrace(); }
}
}
}
Cookies class:
import java.io.*;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieTest extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//Get the current session ID by searching the received cookies.
String cookieid = null;
Cookie[] cookies = req.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equals("REMOTE_USER"))
{
cookieid = cookies[i].getValue();
break;
}
}
}
System.out.println("Cookie Id--"+cookieid);
//If the session ID wasn't sent, generate one.
//Then be sure to send it to the client with the response.
}
//Gets the cookie
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("https://google.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
public void setCookieUsingCookieHandler() {
try {
// instantiate CookieManager
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John H");
// add cookie to CookieStore for a
// particular URL
URL url = new URL("https://google.com");
cookieJar.add(url.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
} catch(Exception e) {
System.out.println("Unable to set cookie using CookieHandler");
e.printStackTrace();
}
}
}
Reason for why i'm using cookies is that i need to access the users credentials in order to download the information.
Many thanks in advance.

Jackson Unhandled Exception?

I am new to android programming, and I was following this tutorial
to create a GCM server program. However, I came across a frustrating bug and would greatly appreciate any help.
This is my POST2GCM class:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;
public class POST2GCM extends Content {
private static final long serialVersionUID = 1L;
public static void post(String apiKey, Content content){
try{
// 1. URL
URL url = new URL("https://android.googleapis.com/gcm/send");
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
//`5.1 Use Jackson object mapper to convert Contnet object into JSON
ObjectMapper mapper = new ObjectMapper();
// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
// 5.3 Copy Content "JSON" into
mapper.writeValue(wr, content);
// 5.4 Send the request
wr.flush();
// 5.5 close
wr.close();
// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have included the "jackson-databind-2.5.1.jar" file but I get the error:
Unhandled Exception: com.fasterxml.jackson.databind.JsonMappingException
on the line mapper.writeValue(wr, content);
What is causing this exception, and how can I fix it?
jackson-databind is a general data-binding package which works on streaming API (jackson-core) implementations. That's why you need to add jackson-core and catch 3 exceptions. writeValue method throws IOException, JsonGenerationException and JsonMappingException.
try {
mapper.writeValue(wr, content);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Hope it will be useful for you.

Jasper Reports: getting JSON data from a post rest service

I am trying to get JSON data from a rest service. I know this is pretty simple for a GET service where you only have to provide the URI and Jasper studio can pull the data but I want to do this for a post rest service that also consumes some JSON input.
Workflow will be something like:
Send userID in request header and some JSON parameters in request
body.
Get JSON data as output.
Use JSON data to build report.
I am new to Jasper and am using Jasper server 6 with Japser Studio 6 but I can't find any documentation to do something like this.
I would appreciate if anyone can point me in the right direction regarding this.
The closes thing I can find is this link. From there I get that I can create a constructor which will get the data from rest service but how do I serve it to the report? Also please note that the JSON object being retrieved here is a bit complex and will have at least 2 lists with any number of items.
EDIT:
Alright so my custom adapter is like this:
package CustomDataAdapter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
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.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONObject;
public class SearchAdapter implements JRDataSource {
/**
* This will hold the JSON returned by generic search service
*/
private JSONObject json = null;
/**
* Will create the object with data retrieved from service.
*/
public SearchAdapter() {
String url = "[URL is here]";
String request = "{searchType: \"TEST\", searchTxt: \"TEST\"}";
// Setting up post client and request.
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
HttpResponse response = null;
post.setHeader("userId", "1000");
post.setHeader("Content-Type", "application/json");
// Setting up Request payload
HttpEntity entity = null;
try {
entity = new StringEntity(request);
post.setEntity(entity);
// do post
response = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Reading Server Response
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new Exception("Search Failed");
}
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String inputLine;
StringBuffer resp = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
resp.append(inputLine);
}
in.close();
this.json = new JSONObject(resp.toString());
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* #see
* net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports
* .engine.JRField)
*/
public Object getFieldValue(JRField field) throws JRException {
// TODO Auto-generated method
// stubhttp://community-static.jaspersoft.com/sites/default/files/images/0.png
return this.json;
}
/*
* (non-Javadoc)
*
* #see net.sf.jasperreports.engine.JRDataSource#next()
*/
public boolean next() throws JRException {
return (this.json != null);
}
/**
* Return an instance of the class that implements the custom data adapter.
*/
public static JRDataSource getDataSource() {
return new SearchAdapter();
}
}
I am able to create an adapter and the Test Connection feature in Jasper Studio also returns true but I cant get it to read any of the fields in the JSON and auto-generate the report. I only get a blank document. FYI the JSON is something like:
{
"key": "value",
"key": "value",
"key": [list],
"key": [list]
}
Well, I feel stupid now but the solution was pretty easy. Turns out you cant just return a JSON object. You need to return the fields and manually add the fields in the report.
For record purposes my final code look like this:
package CustomDataAdapter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
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.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONException;
import org.json.JSONObject;
public class SearchAdapter implements JRDataSource {
/**
* This will hold the JSON returned by generic search service
*/
private JSONObject json = null;
/**
* Ensures that we infinitely calling the service.
*/
private boolean flag = false;
/**
* Will create the object with data retrieved from service.
*/
private void setJson() {
String url = "[URL is here]";
String request = "{\"searchType\": \"Test\", \"searchTxt\": \"Test\"}";
// Setting up post client and request.
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
HttpResponse response = null;
post.setHeader("userId", "1000");
post.setHeader("Content-Type", "application/json");
// Setting up Request payload
StringEntity entity = null;
try {
entity = new StringEntity(request);
post.setEntity(entity);
// do post
response = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Reading Server Response
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
// Thrown Exception in case things go wrong
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String inputLine;
StringBuffer resp = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
resp.append(inputLine);
}
in.close();
String ex = "Search Failed. Status Code: " + statusCode;
ex += "\n Error: " + resp.toString();
throw new Exception(ex);
}
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String inputLine;
StringBuffer resp = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
resp.append(inputLine);
}
in.close();
this.json = new JSONObject(resp.toString());
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* #see
* net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports
* .engine.JRField)
*/
#Override
public Object getFieldValue(JRField field) throws JRException {
// TODO Auto-generated method
// stubhttp://community-static.jaspersoft.com/sites/default/files/images/0.png
try {
return this.json.get(field.getName());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
* (non-Javadoc)
*
* #see net.sf.jasperreports.engine.JRDataSource#next()
*/
#Override
public boolean next() throws JRException {
if (this.json != null && !flag) {
flag = true;
return true;
} else {
return false;
}
}
/**
* Return an instance of the class that implements the custom data adapter.
*/
public static JRDataSource getDataSource() {
SearchAdapter adapter = new SearchAdapter();
adapter.setJson();
return adapter;
}
}

send a variable from java client to php server via Json

I am a beginner in both Java and PHP
I am working on an app that has 2 part:
Android client(Java) both and PHP server.
I tried many of the available tutorials and read about mistakes users made but failed to succeed in any!
This is one of the tutorials I am using:
Java File
package org.postandget;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
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;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Main extends Activity {
TextView tv;
String text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.textview);
text = "";
try {
postData();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void postData() throws JSONException{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/ReceiveLocation.php");
JSONObject json = new JSONObject();
try {
// JSON data:
json.put("name", "Fahmi Rahman");
json.put("position", "sysdev");
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
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();
}
}
text = sb.toString();
}
tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
this is the php file
<?php
include('ConnectionFunctions.php');
Connection();
$json = $_POST['jsonpost'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
echo "\n\n";
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
echo "\n\n";
$name = $data->name;
$pos = $data->position;
echo "Result: \n";
echo "--------------\n";
echo "Name : ".$name."\n Position : ".$pos;
?>
this is the error that appears when i run the php
Notice: Undefined index: HTTP_JSON in C:\xampp\htdocs\ReceiveLocation.php on line 5
JSON: -------------- NULL Array: -------------- NULL
Notice: Trying to get property of non-object in C:\xampp\htdocs\ReceiveLocation.php on line 17
Notice: Trying to get property of non-object in C:\xampp\htdocs\ReceiveLocation.php on line 18
Result: -------------- Name : Position :
Access the JSON data using:
$json = $_POST['jsonpost'];
You were trying to access an invalid field in your php file, it should have been
$json = $_POST['jsonpost'];
OR
$json = $_REQUEST['jsonpost'];
Remember to also sterilize your data from bad input in your php file if you plan to do database work with the data. ALso maybe your localhost path should be changed from
HttpPost httppost = new HttpPost("http://127.0.0.1/ReceiveLocation.php");
TO
HttpPost httppost = new HttpPost("http://10.0.2.2/ReceiveLocation.php");
Hope i helped.
You have a Problem with your code, JSON Data is only added to the header and not to the POST Section of HTTP Request.
So when you output:
print_r(getallheaders());
$headers = getallheaders();
$json = json_decode($headers['json']);
print_r($json);
You should see your data. I right now have not a fix, but i am working on it.

Problem returning an object from an AsyncTask

I have a class (RestClient.java) that extends AsyncTask:
package org.stocktwits.helper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class RestClient extends AsyncTask<String, Void, JSONObject>{
public JSONObject jsonObj = null;
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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();
}
/* This is a test function which will connects to a given
* rest service and prints it's response to Android Log with
* labels "Praeda".
*/
public static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json ) {
this.jsonObj = json;
}
public void setJSONObject(JSONObject jsonFromUI){
this.jsonObj = jsonFromUI;
}
public JSONObject getJSONObject(){
return this.jsonObj;
}
}
I am trying to execute the AsyncTask on my Main class (Main.java):
RestClient rc = new RestClient();
JSONObject json = new JSONObject();
rc.setJSONObject(json);
rc.execute(buildQuery());
json = rc.getJSONObject();
//do some stuff with the json object
try { JSONObject query = json.getJSONObject("query");
//...
}
json is null because it is called before onPostExecute(). How can I get my JSON?
UPDATE:
I need to run this try block in onPostExecute():
try {
JSONObject query = json.getJSONObject("query");
JSONObject results = query.getJSONObject("results");
if (query.getString("count").equals("1")) { // YQL JSON doesn't
// return an array for
// single quotes
JSONObject quote = results.getJSONObject("quote");
Quote myQuote = new Quote();
myQuote.setName(quote.getString("Name"));
myQuote.setSymbol(quote.getString("Symbol"));
myQuote.setLastTradePriceOnly(quote
.getString("LastTradePriceOnly"));
myQuote.setChange(quote.getString("Change"));
myQuote.setOpen(quote.getString("Open"));
myQuote.setMarketCapitalization(quote
.getString("MarketCapitalization"));
myQuote.setDaysHigh(quote.getString("DaysHigh"));
myQuote.setYearHigh(quote.getString("YearHigh"));
myQuote.setDaysLow(quote.getString("DaysLow"));
myQuote.setYearLow(quote.getString("YearLow"));
myQuote.setVolume(quote.getString("Volume"));
myQuote.setAverageDailyVolume(quote
.getString("AverageDailyVolume"));
myQuote.setPeRatio(quote.getString("PERatio"));
myQuote.setDividendYield(quote.getString("DividendYield"));
myQuote.setPercentChange(quote.getString("PercentChange"));
quotesAdapter.add(myQuote);}
Hey You can use listeners to fix this problem.
I've changed the code slightly to use this.
package com.insidetip.uob.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class JSONClient extends AsyncTask<String, Void, JSONObject>{
ProgressDialog progressDialog ;
GetJSONListener getJSONListener;
Context curContext;
public JSONClient(Context context, GetJSONListener listener){
this.getJSONListener = listener;
curContext = context;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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 static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onPreExecute() {
progressDialog = new ProgressDialog(curContext);
progressDialog.setMessage("Loading..Please wait..");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json ) {
getJSONListener.onRemoteCallComplete(json);
progressDialog.dismiss();
}
}
Use in the calling class like this.
JSONClient client = new JSONClient(context, listener);
client.execute(URL);
Dont forget to implement the listener
public interface GetJSONListener {
public void onRemoteCallComplete(JSONObject jsonFromNet);
}
I'm be mistaken by result of doInBackground can be consumed in onPostExecute
doInBackground(Params...), invoked on
the background thread immediately
after on PreExecute() finishes
executing. This step is used to
perform background computation that
can take a long time. The parameters
of the asynchronous task are passed
to this step. The result of the
computation must be returned by this
step and will be passed back to the
last step. This step can also use
publishProgress(Progress...) to
publish one or more units of
progress. These values are published
on the UI thread, in the
onProgressUpdate(Progress...) step.
#Override
protected void onPostExecute(JSONObject json ) {
// DO stuff here ( it's UI thread )
mJsonFromTheActivity = json;
}
execute() always returns the AsyncTask itself. The object you return from doInBackground() is handed to you in onPostExecute().
If you have your asynctask as a nested inner class of your activity, you can set one of your activities variables to the result of your asynctask

Categories

Resources