Please suggest any solution?
I'm new to android.I'm getting error while invoking web service
W/System.errīš java.io.IOException: Method Not Allowed
Here is my activity which calls a web service(method) which takes one string parameter and gives output. I'd be glad if anybody posts code snippet using asynctask becos it is most preferred way to call service in android....
public class closingBalance extends ActionBarActivity {
protected final String NAMESPACE = "http://xxxxx/";
protected final String METHOD_NAME = "getReportDetails";
protected final String URL = "http://xxxxx?wsdl?shop_num=12345";
HttpClient client = new DefaultHttpClient();
try {
HttpResponse res = client.execute(new HttpGet(URL));
StatusLine line = res.getStatusLine();
if(line.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
res.getEntity().writeTo(out);
String response = out.toString();
System.out.println(response);
out.close();
}else{
res.getEntity().getContent().close();
throw new IOException(line.getReasonPhrase());
}
} catch (IOException e) {
e.printStackTrace();
}
}
I advise you to research the Volley tool can be very useful to you.
Transmitting Network Data Using Volley is very simple
https://developer.android.com/training/volley/index.html
Consider using Retrofit library.
Here is a comparison between AsyncTask, Volley and Retrofit
Related
I'm relatively new to Android (I'm an iOS-Developer) and I want to call a Webservice like I'm used to in iOS with NSURLConnectionDelegate's method
didReceiveData:(NSData *)data
I need to get the data incrementally because I'm building a streaming API that gets a lot of JSON data in response and needs to check the data for complete blocks.
Would be great if someone could help me, I've been searching for a while and didn't find a satisfying solution so far.
If you try to call web services in Android you should use the AsyncTask where the request would be made asynchronously. Have a look at the documentation. Every time you're request would be finished the method onPostExecute(Object result) would be called. Thats the method where you can go on with further processes.
The URLConnection documentation contain following example:
URL url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
readStream(in);
finally {
in.close();
}
If i right understood your question, just implement readStream function as you need.
I found out how to do this with the help of a friend and some links.
You need to implement an own ResponseHandler like this:
class ChunkedResponseHandler implements ResponseHandler<String> {
#Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
StringBuffer output = new StringBuffer();
byte[] b = new byte[4096];
int n;
while ((n = stream.read(b)) != -1) {
output.append(new String(b, 0, n));
// do something while input is streaming
}
return output.toString();
}
}
Now you simply have to assign the response handler when starting the request:
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("someURL");
ResponseHandler<String> responseHandler = new ChunkedResponseHandler();
String responseBody = client.execute(postRequest, responseHandler);
I am developing an android application and i need to access the server side which is done as web pages in asp.net
below is the web page URL :
theWebPageURL?action=methodName&email=theEmail
i don't know what methods shall i use to access this URL and send the email parameter to it and get the response.
i searched alot and none worked
can anyone help me please ?
I would recommend reviewing these two similar qustions:
Make an HTTP request with android
How to add parameters to a HTTP GET request in Android?
UPDATE
The below code is a working sample I put together based off of the answers in the two links above; if this helps you, be sure to thank them.
For demonstration, the uri in this sample is being constructed into http://www.google.com/search?q=android.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Construct the URI
String uri = "http://www.google.com/search?";
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("q", "android"));
uri += URLEncodedUtils.format(params, "utf-8");
// Run the HTTP request asynchronously
new RequestTask().execute(uri);
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// result contains the response string.
}
}
}
And, of course, don't forget to add this to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
You need to use http get request
HttpGet
and add this line to your manifest file
<uses-permission android:name="android.permission.INTERNET" />
also, check this link
Can anyone tell me which is the best, ease and flexible method to consume web service from android? I'm using eclipse.
Since you only care about consuming a webservice, I assume you already know how to send data from the web server. Do you use JSON or XML, or any other kind of data format?
I myself prefer JSON, especially for Android.
Your question still lacks some vital information.
I personally use apache-mime4j and httpmime-4.0.1 libraries for web services.
With these libraries I use the following code
public void get(String url) {
HttpResponse httpResponse = null;
InputStream _inStream = null;
HttpClient _client = null;
try {
_client = new DefaultHttpClient(_clientConnectionManager, _httpParams);
HttpGet get = new HttpGet(url);
httpResponse = _client.execute(get, _httpContext);
this.setResponseCode(httpResponse.getStatusLine().getStatusCode());
HttpEntity entity = httpResponse.getEntity();
if(entity != null) {
_inStream = entity.getContent();
this.setStringResponse(IOUtility.convertStreamToString(_inStream));
_inStream.close();
Log.i(TAG, getStringResponse());
}
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
_inStream.close();
} catch (Exception ignore) {}
}
}
I make a request via _client.execute([method], [extra optional params])
The result from the request is put in a HttpResponse object.
From this object you can get the status code and the entity containing the result.
From the entity I take the content. The content would in my case be the actualy JSON string. You retrieve this as an InputStream, convert the stream to a string and do whatever you want with it.
For example
JSONArray result = new JSONArray(_webService.getStringResponse()); //getStringResponse is a custom getter/setter to retrieve the string converted from an inputstream in my WebService class.
Depending on how you build your JSON. mine is nested deeply with objects in the array etc.
But handling this is basic looping.
JSONObject objectInResult = result.getJSONObject(count);//count would be decided by a while or for loop for example.
You can extract data from the current JSON object in this case like:
objectInResult.getString("name"); //assume the json object has a key-value pair that has name as a key.
to parse "JSON" I recommend the following library is the faster and better.
Jackson Java JSON-processor
I am relatively a new Android developer and I am not able to understand how to do this. I have been looking through all the forums, I made some advance but still here I am.
So, what I want to do is a common function that send a POST request to a webpage (it only sends one POST argument) and returns the result as a string.
I have the main thread here
public class AppActivity extends Activity {
HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText(PostData.Result);
}
and I have my HTTPPostData asynchronous class
public class HTTPPostData extends AsyncTask<String, Long, Object> {
String Value = null;
String Result = null;
public HTTPPostData(String query) {
Value = query;
}
#Override
protected String doInBackground(String... params) {
byte[] Bresult = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mypage.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("cmd", Value));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
Bresult = EntityUtils.toByteArray(response.getEntity());
Result = new String(Bresult, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
}
return Result;
}
}
I want to use this function several times (inside the same Activity or share it with other Activities of the same application). I am a little bit messed up at this moment so I need your help. What I understand is that I am asking for the result before the doInBackground() is done, and I get an empty result.
Thanks in advance for your help
Regarding this:
HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText(PostData.Result);
Your problem is that you're treating asynctask like it's just a regular function. It's good that you move webpage loading off the main thread, but if you depend on the result for the very next instruction, then it's not doing you much good, you're still blocking the main program waiting for the result. You need to think of AsyncTask like a 'fire and forget' operation, in which you don't know when, if ever, it will come back.
The better thing to do here would be something like:
HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText("Loading...");
and then in the asynctask:
protected void onPostExecute(String result) {
txtLabel.setText(result);
}
This lets your main thread get on with doing it's business without knowing the result of the asynctask, and then as soon as the data is available the asynctask will populate the text label with the result.
I need post data to server.
I use this code:
HttpClient client = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(serverUrl);
StringEntity se = new StringEntity(data);
httppost.setEntity(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Execute HTTP Post Request
HttpResponse response = client.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
Log.i(TVProgram.TAG, "ErrorHandler post status code: " + statusCode);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
client.getConnectionManager().shutdown();
}
}
But problem is that Android freeze on execute() method, application is blocked out and after some time Android tell me that application doesn't respond.
I tried to debug into SDK classes and it freeze in AbstractSessionInputBuffer class on the line 103 which is
l = this.instream.read(this.buffer, off, len);
I also tried it run the request in separated thread, but the same problem.
I tested it on Android 2.1 (emulator) and Android 2.2 real mobile device.
I also tried to set HTTP proxy and use Fiddler to check HTTP communication data are received by server and server also send correct answer and HTTP code 200. All seems to be ok.
What is wrong please?
UPDATE: When I use AndroidHttpClient which is part of Android 2.2 SDK it works great. But it is not in earlier version of Android. So I include it's source code in my app for now. But AndroidHttpClient use DefaultHTTPClient internally, so problem will be in configuration of DefaultHttpClient.
I am using a POST HTTP request successfully. Here is my code. I removed pieces using handler to display messages etc. and the handler itself.
The POST string is like "&NAME=value#NAME2=value2"...
protected class ConnectingThread implements Runnable
{
Message msg;
private Handler mExtHandler;
private String mData;
private String mUrl;
/**
* #param h (Handler) - a handler for messages from this thread
* #param data (String) - data to be send in HTTP request's POST
* #param url (String) - URL to which to connect
*/
ConnectingThread(Handler h, String data, String url) {
mExtHandler = h;
mData = data;
mUrl = url;
}
public void run() {
try {
// TODO use the handler to display txt info about connection
URL url = new URL(mUrl);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(CONN_TIMEOUT_MILLIS);
conn.setDoOutput(true);
BufferedOutputStream wr = new BufferedOutputStream(conn.getOutputStream());
wr.write(mData.getBytes());
wr.flush();
wr.close();
String sReturn = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int length = conn.getContentLength();
char[] buffer = new char[length];
int read = rd.read(buffer);
if(read == length)
sReturn = new String(buffer);
rd.close();
buffer = null;
// TODO use the handler to use the response
} catch (Exception e) {
//....
}
// TODO use the handler to display txt info about connection ERROR
}
}
Isn't client.execute(httppost); synchronous ?
You probably need to put this in a thread, else it will freeze the UI.
Yes it is being freezed just becoz you haven't implemented this as Asynchronous process. Because while it makes web request, your UI will wait for the response and then it will be updated once the response is received.
So this should be implemented as Asynchronous process, and user should be notified (with progress bar or progress dialog) that there is something happening.
Now, Instead of implementing Runnable class, in android its preferrable and recommended to use AsyncTask, its also known as Painless Threading.
Do you background tasks inside the doInBackground() method.
Do your display type of operations inside onPostExecute() method, like updating listview with fetched data, display values inside TextViews....etc.
Display ProgressBar or ProgressDialog inside the onPreExecute() method.
Use AndroidHttpClient helped me in this situation.
But now complete AndroidHttpClient and DefaultHttpClient are obsolete in current version of Android so it is not important now.