async Task : connect to tcp server and send a string ,close connection - java

I am a beginner in android development,
I have to do the following when a button is clicked using a Async Task.
connect to a specific TCP server using ip and Port and Check if its connected?
on failure show a toast message
on success send a string to the tcp server
close the connection.
I had used the code below for connecting
try
{
s= new Socket("192.168.43.205",20108);
out = new BufferedWriter( new OutputStreamWriter(s.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
catch (UnknownHostException e) {
tv.setText(e.toString());
Log.v("Tcp", e.toString());
}
catch (IOException e) {
tv.setText(e.toString());
Log.v("Tcp",e.toString());
}
catch (Exception e) {
tv.setText(e.toString());
}
but this usually hangs when the server isn't available. Is there a fix for this?

Use AsyncTask to make connection and retrieve data
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.os.AsyncTask;
public class SendDataAsync extends AsyncTask<String, Void, String> {
Context mContext;
public SendDataAsync(Context context){
this.mContext = context;
}
#Override
protected String doInBackground(String... params) {
String str = params[0];
.
.
.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("YOUR_URL");
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
BasicNameValuePair strBasicNameValuePair = new BasicNameValuePair("str", str);
.
.
.
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(strBasicNameValuePair);
.
.
.
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Client Protocol Exception :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("IO Exception :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}

Related

Android Http Get Request

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.

Invoke a method of a web service from a Java (Android) external app

sorry if the question is too easy, but I do not know the answer..
What I have to do is to invoke a method of a web service using a java app.
Here you can find a web service:
http://muovi.roma.it/ws/xml/autenticazione/1
And I want Invoke the method called "autenticazione.Accedi:"
I have a python example that is doing this:
from xmlrpclib import Server
from pprint import pprint
DEV_KEY = 'Inserisci qui la tua chiave'
s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')
token = s1.autenticazione.Accedi(DEV_KEY, '')
res = s2.paline.Previsioni(token, '70101', 'it')
pprint(res)
But I need the same operation in Java... Can anyone help me in this problem?
thank you
I recommend you using this project as a Library.
https://github.com/matessoftwaresolutions/AndroidHttpRestService
It makes you easy deal with apis, control network problems etc.
You can find a sample of use there.
You only have to:
Build your URL
Tell the component to execute in POST/GET etc. mode
Build your JSON
I hope it helps!!!
package com.example.jojo.gridview;
import android.util.Log;
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;
/**
* Created by jojo on 12/10/15.
*/
public class WebService {
String url="http://192.168.1.15/Travel_Dairy/";
String invokeGetWebservice(String webUrl)
{
String result = "";
webUrl=webUrl.replace(" ","%20");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(webUrl);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputstream= entity.getContent();
BufferedReader bufferedreader = new BufferedReader(
new InputStreamReader(inputstream), 2 * 1024);
StringBuilder stringbuilder = new StringBuilder();
String currentline = null;
try {
while ((currentline = bufferedreader.readLine()) != null) {
stringbuilder.append(currentline + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
result = stringbuilder.toString();
Log.e("Result", result);
inputstream.close();
return result;
}
} catch (ClientProtocolException e1) {
Log.e("ClientProtocolException", e1.toString());
return result;
} catch (IOException e1) {
Log.e("IOException", e1.toString());
return result;
}
return result;
}
public List<DataModel> getTrips() {
String getname="view_details.php?";
String completeurlforget=url+getname;
//String seturl= "ur_id="+userid;
//String finalurl=completeurlforget+seturl;
String result=invokeGetWebservice(completeurlforget);
try {
JSONArray jsonarry=new JSONArray(result);
List<DataModel> ar=new ArrayList();
for(int i=0;i<jsonarry.length();i++)
{
JSONObject jsonobj=jsonarry.getJSONObject(i);
DataModel user=new DataModel();
user.setName(jsonobj.getString("name"));
user.setImage(jsonobj.getString("image"));
ar.add(user);
}
return ar;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Json parse from URL

I am getting java.lang.NullPointerException when I run this. Does anyone know why this is happening and how I can fix it?
Please take a look at my code and let me know if you have any suggestions.
{"begin":[{"id":1,"name":"Andy","size":1}],"open":[{"id":1,"name":"Tom","size":2}]}
Fragment
public class MainFragment extends Fragment {
public MainFragment() {}
//URL to get JSON Array
private String url = "URL...";
//JSON Node Names
private static final String TAG_BEGIN = "begin";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
JSONArray begin = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
begin = json.getJSONArray(TAG_BEGIN);
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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;
}
}
Error:
E/JSON Parserīš• Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
FATAL EXCEPTION: main
java.lang.NullPointerException
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:399)
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:373)
Which is...
begin = json.getJSONArray(TAG_BEGIN);
and...
private class JSONParse extends AsyncTask<String, String, JSONObject> {
EDIT (Answer)
JSONParser
Inside of JSONParser I changed my code to this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpUriRequest request = new HttpGet(url);
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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;
}
}
Inside of onPostExecute
JSONArray begin = json.getJSONArray(TAG_BEGIN);
for (int i = 0; i < begin(); i++) {
try {
JSONObject b = = begin(i);
String id = b.getString(TAG_ID);
String name = b.getString(TAG_NAME);
String size = b.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
First make sure your JSONObject is not null. Then slowly transverse line by line based off the type.
JSONArray begin = json.getJSONArray(TAG_BEGIN);
Then possibly do something like this?
for(int n = 0; n < begin.length(); n++)
{
JSONObject object = begin.getJSONObject(n);
// query through the array
String id = object.getString(TAG_ID);
String name = object.getString(TAG_NAME);
String size = object.getString(TAG_SIZE);
//Now do something with the strings
}
Of course you'd do the same thing with the TAG_OPEN. Let me know if this works, I'll gladly help as much as possible.
the error shows that the return string of you http request is not only the json data
something like <!DOCTYPE are includeed
please check you are request the right url, and the server handle the request correctly
you can use your browser visit the url you request and check the return result
I am not using a fragment but here is similar solution.
Change your url and key values for retrieving values from json. I didn't have your url so i used some other. Please check it out. Same concept except i am not using fragments but this json parsing code works just fine.
First of all, you have to deal with the network on main thread exception
Add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
in your class,
and
ADD this to ManiFestFile:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.Java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.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.os.StrictMode;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Making HTTP request
String url = "http://api.androidhive.info/contacts/";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
JSONArray begin = json.getJSONArray("contacts");
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString("id");
String name = c.getString("name");
String size = c.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser.Java
package com.example.test;
import android.os.StrictMode;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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;
}
}

HTTPclient POST with problematic web site

I'm trying to retrive some data from a web site.
I wrote a java class which seems to work pretty fine with many sites but it doesn't work with this particular site, which use extensive javascript in the input fomr.
As you can see from the code I specified the input fields taking the name from the HTML source, but maybe this website doesn't accept POST request of this kind?
How can I simulate an user-interaction to retrieve the generated HTML?
package com.transport.urlRetriver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class UrlRetriver {
String stationPoller (String url, ArrayList<NameValuePair> params) {
HttpPost postRequest;
HttpResponse response;
HttpEntity entity;
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
postRequest = new HttpPost(url);
postRequest.setEntity((HttpEntity) new UrlEncodedFormEntity(params));
response = httpClient.execute(postRequest);
entity = response.getEntity();
if(entity != null){
InputStream inputStream = entity.getContent();
result = convertStreamToString(inputStream);
}
} catch (Exception e) {
result = "We had a problem";
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
void ATMtravelPoller () {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2);
String url = "http://www.atm-mi.it/it/Pagine/default.aspx";
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_s", "Viale romagna 1"));
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_e", "Viale Toscana 20"));
params.add(new BasicNameValuePair("sf_method", "POST"));
String result = stationPoller(url, params);
saveToFile(result, "/home/rachele/Documents/atm/out4.html");
}
static void saveToFile(String toFile, String pos){
try{
// Create file
FileWriter fstream = new FileWriter(pos);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toFile);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
At my point of view, there could be javascript generated field with dynamic value for preventing automated code to crawl the site. Send concrete site you want to download.

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