AsyncTask to display Response form WCF - java

I wrote a Restful WCF service and it is deployed on IIS. I have been attempting to consume the WCF Service using a AsyncTask Thread. I built the thread in to the main UI class so that I can update the GUI.
public class ServiceRunning extends AsyncTask<String, Void, String>{
private Exception exception;
String line = "";
public void setLine(String line)
{
this.line = line;
}
public String getLine()
{
return line;
}
#Override
protected String doInBackground(String... url) {
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri = new URI(url[0]);
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// while ((line = rd.readLine()) != null) {
// Log.d("****Status Line***", "Webservice: " + line);
// }
while((line = rd.readLine()) != null)
{
setLine(line);
Log.d("****Status Line***", "Webservices: " + getLine());
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "String :" + line;
}
protected void onPostExecute(String result) {
TextView txt = (TextView)findViewById(R.id.textView1);
txt.setText(getLine());
}
}
In the code, I write the response to a String and I attempt to display it after execution. For some resound, when I run the program I don't get the response, I get a blank TextView but the message displays in the Eclipse LogCat. I cant find the problem, what causes this?

AsyncTask is tied to the activity kicking it off. If you rotate the device or the app goes into the background, is added or removed from a dock, the original activity is destroyed. The AsyncTask continues though and responds to the original activity that is no longer visible.
You are better off using an IntentService or Service to call web services, it is a much more reliable pattern.

Related

My Android app can't connect to server

I'm tying to read data from server I'm using xampp) but the data is empty
this is my connect activity:
public String link="";
public AsyncTaskConnect(String link){
this.link=link;
}
#Override
protected Object doInBackground(Object[] params) {
try{
URL url=new URL(link);
URLConnection connection=url.openConnection();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
builder.append(line);
}
MainActivity.data=builder.toString();
}catch (Exception e){
}
return "";
}
this is main activity:
public static String data="";
TextView txthello;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txthello=(TextView)findViewById(R.id.txthello);
new AsyncTaskConnect("http://192.168.1.2/digikala/test.php").execute();
txthello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,data,Toast.LENGTH_LONG).show();
}
});
}
but it doesn't work, what should I do?
but the data is empty
Because execute is not a blocking call.
Assuming you can actually reach the server, MainActivity.data is an empty String until after the Asynctask onPostExecute
You can either use Volley, Okhttp, Retrofit, etc to simplify your networking code
Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
or add callbacks into your Asynctask
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
Using HttpURLConnection, it extends your URLConnection so I am changing just a little to your code. Given you have your query in the String variable link, this should work just as fine.
try {
URL url = new URL(link);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
Log.i(TAG, "POST Response Code: " + responseCode);
//Takes data only if response from WebService is OK
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
//Stores input line by line in response
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
if you follow this snippet, response is the string which contains all of the response you get from your webservice, you can further convert it to JSON if you want.
Hope it works!

No response from HTTP request

i have written an android app which post data to my database. The app should access an webservice which post the data to the database. the webservice works fine. ive testet it with my browser, he is already on the server. now i want my app to execute the webservice. but that doesnt work. My debugger doesnt work too so im not able to debug. here is my code to for accessing the webservice. any ideas??
public class PostBlog extends AsyncTask<String, Void, String> {
String BlogURL;
public PostBlog(String insertBlogURL) {
BlogURL = insertBlogURL;
}
#Override
protected String doInBackground(String... params) {
postBlogData(BlogURL);
return null;
}
public void postBlogData(String url) {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
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();
result = sb.toString();
} catch (Exception e) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
The Class is called from my main Activity by
new PostBlog(insertBlogURL).execute("");
Is there another easier way to execute my ".jsp?asdd=sdsd" file on the server?
Thanks for your ideas.
Instead of doing :
new PostBlog(insertBlogURL).execute("");
Change your constructor and retrieve the url from the doInBackground method, by doing params[0]
Then initiate the download like this
PostBlog blogPoster = new PostBlog();
try {
blogPoster.execute(insertBlogURL);
} catch (InterruptedException e) {} catch (ExecutionException e) {}
I should say this is a modified snippet of code from my own project, so it might not work exactly the way you expect.

HTTP POST request works on emulator, but doesn't on real device

I built a simple app which gets data from a remote database using HTTP POST requests. I decided to change its layout, but now the requests I realize doesn't work on a real device.
I simply change the layout and copied the same classes on this new project. I can't understand what's wrong. When I use the app it stops on the splash screen activity and waits there. I looked into the code and I noticed that I stops when are performed the POST requests.
When I execute the project on the emulater, it works perfectly.
This is my class:
public class MyHttpPostRequest extends AsyncTask<String, Void, String[]> {
private String link;
private String querySql;
public MyHttpPostRequest(String remoteLink, String richiestaSql) {
this.link = remoteLink;
this.querySql = richiestaSql;
}
#Override
protected String[] doInBackground(String... params) {
// Create a new HttpClient and Post Header
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(this.link);
BufferedReader bufferedReader = null;
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("query", this.querySql));
StringBuffer stringBuffer = null;
String[] token = new String[600];
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
request.setEntity(entity);
HttpResponse response= httpClient.execute(request);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
stringBuffer = new StringBuffer("");
String line = "";
String LineSeparator = System.getProperty("line.separator");
int i=0;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line + LineSeparator);
token[i] = line + LineSeparator;
i++;
}
bufferedReader.close();
} catch(Exception e){
}
return token;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
}
public void eseguiRichiesta(){
this.execute(this.link, this.querySql);
}
public void setValues(String remoteLink, String richiestaSql){
this.link = remoteLink;
this.querySql = richiestaSql;
}
public void setLink(String link){
this.link = link;
}
public void setRequest(String requestSQL){
this.querySql = requestSQL;
}
}

Send an HttpPost request from Android, read Post from PHP

As I'm progressing through my Android learning in some spare time, I've encountered a strange behaviour of HttpPost request.
What I'm trying to achieve:
Make a simple POST request from Android application to Apache web-server running on my development PC and display the POSTed data from PHP script to which the form is sent.
My Android app's Java code resides inside an Activity as an AsyncTask as following:
private class DoSampleHttpPostRequest extends AsyncTask<Void, Void, CharSequence> {
#Override
protected CharSequence doInBackground(Void... params) {
BufferedReader in = null;
String baseUrl = "http://10.0.2.2:8080/android";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(baseUrl);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("login", "someuser"));
postParameters.add(new BasicNameValuePair("data", "somedata"));
UrlEncodedFormEntity form = new UrlEncodedFormEntity(postParameters);
request.setEntity(form);
Log.v("log", "making POST request to: " + baseUrl);
HttpResponse response = httpClient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
} catch (Exception e) {
return "Exception happened: " + e.getMessage();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(CharSequence result) {
// this refers to a TextView defined as a private field in the parent Activity
textView.setText(result);
}
}
My PHP code is the following:
<?php
echo "Hello<br />";
var_dump($_SERVER);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Page was posted:<br />";
foreach($_POST as $key=>$var) {
echo "[$key] => $var<br />";
}
}
?>
And finally the problem:
As you can see, the $_SERVER contents is dumped, and in the output $_SERVER["REQUEST_METHOD"] has value GET despite the fact that I was actually making a POST request. Even if I try to dump the contents of $_POST, it's empty.
What am I doing wrong? Thanks in advance.
You might need to specify a trailing slash at the end of the URL.
Often Apache redirects requests that don't end in trailing slashes so that they do contain a trailing slash. That redirect is a GET redirect (without some tweaking), so all POST data is lost.

Post JSON in android

I want to post String data over HttpClient in android
but i'm tired after receive response status code 503 - service unavailable and
return response as Html code for our url.
I write in the following Code in JAVA Application and i return the data but when I write the same code in Android Application i receive an exception file I/O not found, I'm Puzzled for this case:
public void goButton(View v)
{
try{
URL url = new URL("https://xxxxxxxxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Test ts= new ApiRequest("null","getUserbyID",new String[] { "66868706" });
String payLoad = ts.toString(); //toSting is override method that create //JSON Object
System.out.println("--->>> " + payLoad);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("=================>>> "+ payLoad);
wr.write(payLoad);
wr.flush();
BufferedReader rd = new BufferedReader(new nputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("-->> " + line);
response += line;
}
wr.close();
rd.close();
System.out.println("=================>>> "+ response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=================>>> " + e.toString());
throw new RuntimeException(e);
}
I try to put this code in AsynTask, Thread but i receive the same response status code.
I write in the following Android code as an example data
public void goButton(View v)
{
try{
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
String url = "https://xxxxxxxxxxxxx";
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
json.put("service","null");
json.put("method", getUserByID.toString());
json.put("parameters", "1111");
System.out.println(">>>>>>>>>>>" + json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
String response = client.execute(post);
if (response != null) {
String temp = EntityUtils.toString(response.getEntity());
System.out.println(">>>>>>>>>>>" + temp);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(">>>>>>>>>>>" + e.getMessage());
}
}
}).start();
}
Please Help me to find solution for this problem :(
Thank you in advance
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
This code snippet ,
Android device will send the data via URL towards Server
now server needs to fetch that data from the URL
Hey Mohammed Saleem
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say ASP.NET platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want

Categories

Resources