I want my android app to establish a connection to a website and through code navigate the website in background. From what I understand, the first step is to get html source code of the site I wish to navigate which I managed to do through this code:
public class HttpTest extends Activity {
private TextView tvCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http_layout);
tvCode = (TextView)findViewById(R.id.tvHTMLCode);
String s = null;
try {
GetHtmlSourceCode html = new GetHtmlSourceCode();
html.execute("http://www.youtube.com");
s = html.get();
}
catch (Exception e) {
e.printStackTrace();
tvCode.setText("Error");
}
if (s != null)
tvCode.setText(s);
}
private class GetHtmlSourceCode extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
HttpURLConnection conn = null;
String content = "";
try {
url = new URL(params[0]);
conn = (HttpURLConnection)url.openConnection();
InputStream in = conn.getInputStream();
int data = in.read();
while (data != -1) {
char c = (char) data;
data = in.read();
content += c;
}
}
catch (Exception e) {
e.printStackTrace();
return "error";
}
finally {
conn.disconnect();
return content;
}
}
}
}
(Youtube is used just as an example).
After getting the source code from youtube.com, I want my app to input something in the search box and then click the search button.
From what I understand I need to send a POST request to youtube to fill the search box, another POST to press the button and finally a GET to get the html source code of the page with the search result. However the deprecation of the HttpClient and HttpPost classes with which these problems appear to have been solved, my limited english vocabulary and my general ignorance on the subject make it very difficult to find the solution myself.
Can someone help?
Try using the following code
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
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 android.os.AsyncTask;
public class Request extends AsyncTask<String, String, String>{
private HttpClient httpclient = new DefaultHttpClient();
private HttpResponse response;
private String responseString ;
#Override
protected String doInBackground(String... uri) {
StatusLine statusLine = response.getStatusLine();
try {
response = httpclient.execute(new HttpGet(uri[0]));
statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//TO Do
}
}
To make request, use the following code
new RequestTask().execute("http://yourwebsite.com");
Related
I'm a newbie at android development. I'm trying to send a GET request to an URL. I wrote the below code.
public void searchProducts(View v)
{
//String txtSearchTerm = ((EditText)findViewById(R.id.txtsearch)).getText().toString();
//String termCleaned = txtSearchTerm.replace(' ', '+').toString();
AlertDialog alertMessage = new AlertDialog.Builder(this).create();
alertMessage.setTitle("Loading");
alertMessage.setMessage(GET("http://webkarinca.com/sample.json"));
alertMessage.show();
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
{
result = convertInputStreamToString(inputStream);
}
else
{
result = "Did not work!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I already put imports head of the class. There they are
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
It doesn't work and at the Problems section it shows as a warning
The type HttpGet is deprecated
The type HttpResponse is deprecated
Try this. it worked for me.
first must implement this on build.gradle: app
implementation("com.squareup.okhttp3:okhttp:4.8.0")
then, use this method
String run(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Finally, call it on onCreate method
run("enter your URL here");
try this
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import android.content.Context;
import com.jivebird.settings.CommonMethods;
public class Connecttoget {
public static String callJson(Context context,String urlstring){
String data=null;
try {
URL url = new URL(urlstring);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
data = convertStreamToString(stream);
stream.close();
}catch(SocketTimeoutException e){
CommonMethods.createAlert(context, "Sorry, network error", "");
}
catch (Exception e) {
e.printStackTrace();
}
return data;
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
Can you try the below code,if it helps.
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
InputStream inStream = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null) {
response += temp;
}
object = (JSONObject) new JSONTokener(response).nextValue();
} catch (Exception e) {
this.mException = e;
} finally {
if (inStream != null) {
try {
// this will close the bReader as well
inStream.close();
} catch (IOException ignored) {
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Try this code. This worked for me.
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class ServerTest extends Activity {
private String TAG = "test";
private String url = "http://webkarinca.com/sample.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Download().execute();
}
public class Download extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
}
}
}
Also make sure you have added this to manifest,
<uses-permission android:name="android.permission.INTERNET" />
and also make sure you are connected to the internet.
Ive made edits since the orignal post Im making an android app that connects to an JSON API. Everything so far works ok except if there is a delay from the server. The UI of course can stop responding if it takes too long. Ive read that asynctask can solve my problem. Ive had a really ard time with the examples though.
Here is the restclient class making the http calls... parsing the json and storing custom objects to a public list that my other class can access.
package com.bde.dgcr;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class RestClient {
static List<ResponseHolder> list = new ArrayList<ResponseHolder>();
protected Context context = this.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();
}
/* 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 void connect(String url) {
AsyncTask<String, Void, Void> connection = new AsyncTask<String, Void, Void>() {
protected Context context;
#Override
protected Void doInBackground(String... params) {
// Prepare a request object
HttpGet httpget = new HttpGet(params[0]);
// Execute the request
HttpResponse response;
HttpClient httpclient = new DefaultHttpClient();
try {
list.clear();
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 the response does not enclose an entity, there is no need
// to worry about connection release
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);
JSONArray jsonArray = new JSONArray(result);
// A Simple JSONObject Parsing
for (int i = 0; i < (jsonArray.length()); i++) {
JSONObject json_obj = jsonArray.getJSONObject(i);
ResponseHolder rh = new ResponseHolder(json_obj);
list.add(rh);
}
instream.close();
}
} 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 void onPostExecute(Void aVoid) {
ListView listView1;
super.onPostExecute(aVoid); //To change body of overridden methods use File | Settings | File Templates.
ResponseHolderAdapter adapter = new ResponseHolderAdapter(context, R.layout.listview_item_row, RestClient.list);
listView1 = (ListView) findViewById(R.id.listView1);
View header = (View) getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
};
connection.execute(url);
}
}
Here is the class calling the static connect method and using the list for an adapter to go in a list view.
public class JsonGrabber extends Activity {
private final String API_KEY = "key";
private final String SECRET = "secret";
private String state;
private String city;
private String country;
private static String mode;
private String md5;
private String url;
CourseSearch cs;
private ListView listView1;
/**
* Called when the activity is first created.
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
Bundle extras = getIntent().getExtras();
state = extras.getString("state");
city = URLEncoder.encode(extras.getString("city"));
country = extras.getString("country");
mode = extras.getString("mode");
md5 = MD5.getMD5(API_KEY + SECRET + mode);
System.out.println(md5);
url = "http://www.api.com/?key=" + API_KEY + "&mode=" + mode + "&id=1&sig=" + md5;
String findByLocUrl = "http://www.api.com/?key=" + API_KEY + "&mode=" + mode + "&city=" + city + "&state=" + state + "&country=" + country + "&sig=" + md5;
System.out.println(findByLocUrl);
RestClient rc = new RestClient();
rc.connect(findByLocUrl);
//RestClient.connect(findByLocUrl);
/* if (RestClient.list.isEmpty())
{
setContentView(R.layout.noresults);
} else
{
ResponseHolderAdapter adapter = new ResponseHolderAdapter(this, R.layout.listview_item_row, RestClient.list);
listView1 = (ListView) findViewById(R.id.listView1);
View header = (View) getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
*/
}
}
Somehow Im supposed to mesh all this up into using an innerclass extending asyctask to do the API calls in the background parse the json add to my list and set up the adapter. I know i may have some object orientation problems and was hoping before i continue on with my app that you guys can make sure im going in the right direction. I have a few other classes I didnt include. Let me know if it will make more sense if I added the other classes. Thanks In Advance for any help you guys/girls may be able to offer.
You can rewrite your connect method using an AsyncTask like this:
public static void connect(String url) {
HttpClient httpclient = new DefaultHttpClient();
AsyncTask<String, Void, Void> connection = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... params) {
// Prepare a request object
HttpGet httpget = new HttpGet(params[0]);
// Execute the request
HttpResponse response;
try {
list.clear();
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 the response does not enclose an entity, there is no need
// to worry about connection release
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);
JSONArray jsonArray = new JSONArray(result);
// A Simple JSONObject Parsing
for (int i = 0; i < (jsonArray.length()); i++) {
JSONObject json_obj = jsonArray.getJSONObject(i);
ResponseHolder rh = new ResponseHolder(json_obj);
list.add(rh);
}
instream.close();
}
}
} 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();
}
connection.execute(url);
}
If you want to do it right, you should use a contentprovider, service, and a database, here's a good tutorial:
http://mobile.tutsplus.com/tutorials/android/android-fundamentals-downloading-data-with-services/
The type Enum is not generic; it cannot be parameterized with arguments <RestClient.RequestMethod>
I've this error in the following code ..
package ayanoo.utility;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.util.Log;
public class RestClient {
public enum RequestMethod
{
GET,
POST
}
private Vector <NameValuePair> params;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new Vector<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws IOException
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "/";
for(NameValuePair p : params)
{
//String paramString = p.getName() + "=" + p.getValue();
String paramString = p.getValue();
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
Log.d("URL See:",url + combinedParams);
URL urlObject = new URL(url + combinedParams);
//URL urlObject = new URL("http://www.aydeena.com/Services/Search.svc/JSON/SearchByText/1");
executeRequest(urlObject);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(URL urlObject) throws IOException{
HttpURLConnection con = null;
con = (HttpURLConnection) urlObject.openConnection();
con.setReadTimeout(10000 /* milliseconds */);
con.setConnectTimeout(15000 /* milliseconds */);
con.setRequestMethod("GET");
//con.addRequestProperty("Referer",
// "http://www.pragprog.com/titles/eband/hello-android");
con.setDoInput(true);
// Start the query
con.connect();
response = convertStreamToString(con.getInputStream());
Log.d("Response:", response);
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
Log.d("Test URL:", url);
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private 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();
}
}
what's the problem ??? !
I had the same problem, and it turned out that it was because the standard lib was not in the eclipse class path for the project. Just go into Build Path -> Add Libraries and add the JRE System Library
Are you sure the Java compiler is set to 1.5 (default for android) or better? If you are using Eclipse you can see that from the preferences.
I had the same problem.
I only had one error in my project which was the "is not generic one'.
After I commented out the Enum code I found a lot more errors.
There seemed to be some kind of hold-up. Only after fixing the other errors and then removing the comments did it work.
Yes I also saw this error message for a project that was previously working fine.
I checked the compiler version (I am using 1.6) as well as the system library (it is already being used) to no avail.
Finally I just closed the project and then re-opened it, and then the problem went away. Sounds like an Eclipse bug to me.
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
I'm doing a Get and Post method for an android project and I need to "translate" HttpClient 3.x to HttpClient 4.x (using by android).
My problem is that I'm not sure of what I have done and I don't find the "translation" of some methods...
This is the HttpClient 3.x I have done and (-->) the HttpClient 4.x "translation" if I have found it (Only parties who ask me problems) :
HttpState state = new HttpState (); --> ?
HttpMethod method = null; --> HttpUriRequest httpUri = null;
method.abort(); --> httpUri.abort(); //httpUri is a HttpUriRequest
method.releaseConnection(); --> conn.disconnect(); //conn is a HttpURLConnection
state.clearCookies(); --> cookieStore.clear(); //cookieStore is a BasicCookieStore
HttpClient client = new HttpClient(); --> DefaultHttpClient client = new DefaultHttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT) --> HttpConnectionParams.setConnectionTimeout(param, SOCKET_TIMEOUT);
client.setState(state); --> ?
client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); --> HttpClientParams.setCookiePolicy(param, CookiePolicy.RFC_2109);
PostMethod post = (PostMethod) method; --> ?
post.setRequestHeader(...,...); --> conn.setRequestProperty(...,...);
post.setFollowRedirects(false); --> conn.setFollowRedirects(false);
RequestEntity tmp = null; --> ?
tmp = new StringRequestEntity(...,...,...); --> ?
int statusCode = client.executeMethod(post); --> ?
String ret = method.getResponsBodyAsString(); --> ?
Header locationHeader = method.getResponseHeader(...); --> ?
ret = getPage(...,...); --> ?
I don't know if that is correct.
This has caused problems because the packages are not named similarly, and some methods too.
I just need documentation (I haven't found) and little help.
Here are the HttpClient 4 docs, that is what Android is using (4, not 3, as of 1.0->2.x). The docs are hard to find (thanks Apache ;)) because HttpClient is now part of HttpComponents (and if you just look for HttpClient you will normally end up at the 3.x stuff).
Also, if you do any number of requests you do not want to create the client over and over again. Rather, as the tutorials for HttpClient note, create the client once and keep it around. From there use the ThreadSafeConnectionManager.
I use a helper class, for example something like HttpHelper (which is still a moving target - I plan to move this to its own Android util project at some point, and support binary data, haven't gotten there yet), to help with this. The helper class creates the client, and has convenience wrapper methods for get/post/etc. Anywhere you USE this class from an Activity, you should create an internal inner AsyncTask (so that you do not block the UI Thread while making the request), for example:
private class GetBookDataTask extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(BookScanResult.this);
private String response;
private HttpHelper httpHelper = new HttpHelper();
// can use UI thread here
protected void onPreExecute() {
dialog.setMessage("Retrieving HTTP data..");
dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(String... urls) {
response = httpHelper.performGet(urls[0]);
// use the response here if need be, parse XML or JSON, etc
return null;
}
// can use UI thread here
protected void onPostExecute(Void unused) {
dialog.dismiss();
if (response != null) {
// use the response back on the UI thread here
outputTextView.setText(response);
}
}
}
The easiest way to answer my question is to show you the class that I made :
public class HTTPHelp{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private boolean abort;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
public HTTPHelp(){
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if(httpClient!=null){
System.out.println("Abort.");
httpPost.abort();
abort = true;
}
} catch (Exception e) {
System.out.println("HTTPHelp : Abort Exception : "+e);
}
}
public String postPage(String url, String data, boolean returnAddr) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
return ret;
}
}
I used this tutorial to do my post method and thoses examples
Well, you can find documentation on that version of HTTPClient here; it's especially useful to go through the example scenarios they present.
I unfortunately don't know version 3 of HTTPClient so I can't give direct equivalences; I suggest you take what you're trying to do and look through their example scenarios.
package com.service.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
{
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/GetSubscriptionReportNames";//"http://tempuri.org/FahrenheitToCelsius";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME1 = "GetSubscriptionReportNames";//"FahrenheitToCelsius";
private static String URL = "http://icontrolusa.com:8040/iPhoneService.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
ArrayList<String> headlist = new ArrayList<String>();
ArrayList<String> reportlist = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
//Get the first property and change the label text
txtCel.setText(result.getProperty(0).toString());
Log.e("err ","output is :::: "+result.getProperty(0).toString());
parseSON();
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
private void parseSON() {
headlist.clear();
reportlist.clear();
String text = txtCel.getText().toString() ;//sb.toString();
Log.i("######", "###### "+text);
try{
JSONObject jobj = new JSONObject(text);
JSONArray jarr = jobj.getJSONArray("Head");
for(int i=0;i<jarr.length();i++){
JSONObject e = jarr.getJSONObject(i);
JSONArray names = e.names();
for(int j=0;j<names.length();j++){
String tagname = names.getString(j);
if (tagname.equals("ReportID")) {
headlist.add(e.getString("ReportID"));
}
if (tagname.equals("ReportName")) {
reportlist.add(e.getString("ReportName"));
}
}
}
} catch(JSONException e){
Log.e("retail_home", "Error parsing data "+e.toString());
}
Log.d("length ", "head lenght "+headlist.size());
Log.d("value is ", "frst "+headlist.get(0));
Log.d("length ", "name lenght "+reportlist.size());
Log.d("value is ", "secnd "+reportlist.get(0));
}
}