Creating an HTTP connection via Android - android

I am creating an HTTP client to execute a PHP file in my server and this is the code:
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yasinahmed.cpa10.com/sendnoti.php");
HttpResponse response = httpclient.execute(httppost);
Toast.makeText(GCMMainActivity.this, "Done", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(GCMMainActivity.this, "error", Toast.LENGTH_LONG).show();
}
Many times I used this code and it's working without a problem, but this time when I execute the code it always go to the exception and prints the error. This time, I used AVD with Google API level 17, so is this the problem or is there another problem in the code?

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:
class Preprocessing extends AsyncTask<String, Void, Boolean> {
protected Boolean doInBackground(String... urls) {
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yasinahmed.cpa10.com/sendnoti.php");
HttpResponse response = httpclient.execute(httppost);
return true;
}
catch(Exception e)
{
return false;
}
}
protected void onPostExecute(Boolean result) {
if(result)
Toast.makeText(GCMMainActivity.this, "Done", Toast.LENGTH_LONG).show();
else
Toast.makeText(GCMMainActivity.this, "error", Toast.LENGTH_LONG).show();
}
}
Call this class in your Activity:
new Preprocessing ().execute();
Don't forget to add this to AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>

It would help to know the error. But since I have to guess, my bet is that you are trying to execute this code on the main event thread (a.k.a. the UI thread). That was always wrong and as of API level 11, it will cause a NetworkOnMainThreadException to be thrown. See the document Designing for Responsiveness for the proper way to handle networking in Android.

Related

android HTTP POST error

Ok so I created a method in a new class and called it from my activity in try catch block, and when I call it and pass my string value my issue appeared...
My issue started after executing the below method after:
HttpResponse httpresponse = httpclient.execute(httppostreq);
It went to the catch (IOException e) in my activity and when I tried to print the response string it gave me the a response from the server !!!!
So the issue is when I try to pass value to the POST it should return some data but it failed and it's returning the empty message from the server
Hint :
The empty message will appear if there were no values
jsonobj.put("screenType", requestString);
So did i passed the value or not ??? and why it's causing exception ??
public void postData(String requestString) throws JSONException, ClientProtocolException, IOException {
// Create a new HttpClient and Post Header
DefaultHttpClient httpclient = new DefaultHttpClient();
JSONObject jsonobj = new JSONObject();
jsonobj.put("screenType", requestString);
//jsonobj.put("old_passw", "306");
HttpPost httppostreq = new HttpPost("mysite.org");
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);
Log.i("in try", httpresponse.toString());
String responseText=null;
try {
responseText=EntityUtils.toString(httpresponse.getEntity());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.i("in Exception",e.toString());
Log.i("arse exception", httpresponse.toString());
}
}
i also added the internet permisssion
<uses-permission android:name="android.permission.INTERNET" />
You can't make network requests on the main thread. You'll get the error you are seeing now. You need to use either AsyncTask or you need to create a new thread. Personally, I'd use AsyncTask. When you use AsyncTask you can use the onPostExecute method to return the value to the main thread.
See : NetworkOnMainThreadException
As vincent said you can't execute network requests in the UI thread, it will give you a weird exception, but rather than using an AsyncTask which will be destroyed if your activity rotates as this Infographic shows, I can recommend you to use Robospice its the best network framework I have used and it's very easy to use, Good Luck.

HTTP Response in Android - NetworkOnMainThreadException [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I want to check the HTTP response of a certain URL before loading into a webview. I only want to load webview if http response code is 200. This is a workaround for intercepting http errors. I have below:
HttpGet httpRequest = new HttpGet( "http://example.com");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
int code = response.getStatusLine().getStatusCode();
But I encountered the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo
android.os.NetworkOnMainThreadException
How to fix it? Or any workaround to interept http errors in webview? Thanks
android.os.NetworkOnMainThreadException occurs whenever you try to make long running tasks/process on Main UI Thread directly.
To resolve this issue, cover your webservice call inside AsyncTask. FYI, AsyncTask in android known as Painless Threading which means developer don't need to bother about Thread management. So Go and implement web API call or any long running tasks using AsyncTask, there are plenty of examples available on the web.
Update:
I only want to load webview if http response code is 200.
=> Based on your requirement, I would say include your code inside doInBackground() method and return status code value, Which you can check inside onPostExecute(). Now here you are getting status code value 200/201 then you can load WebView.
class HTTPRequest extends AsyncTask<int, Void, void> {
protected int doInBackground() {
try {
HttpGet httpRequest = new HttpGet( "http://example.com");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
int code = response.getStatusLine().getStatusCode();
return code;
} catch (Exception e) {
e.printstacktrace();
}
}
protected void onPostExecute(int code) {
// TODO: check this.exception
// retrieve your 'code' here
}
}
You are getting this Exception because you are carrying out a heavy Computation i.e Acessing Network in your case on UI Thread.
You should never do this .
Rather you can move this code to background Java Thread :
Try :
private void doNetworkCompuation()
{
new Thread(new Runnable() {
#Override
public void run() {
HttpGet httpRequest = new HttpGet( "http://example.com");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
int code = response.getStatusLine().getStatusCode();
}).start();
}
Try executing this code in Async Thread.
You can have a refrence from here:
How to fix android.os.NetworkOnMainThreadException?
You are not allowed to execute network requests on the main thread. You have to use a different thread for making this requests. You should use the AsyncTask, for an example look here.

Android Http Request Issue with version 4.0.3

I'm getting stuck with http request using HttpClient that is working fine with 2.2 or 2.3.X versions. But it is giving me 401 error when I will tried to send that request from my android tablet with version 4.0.3
Here is my code that I have implemented.
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost("MYURL");
json.put("username", username);
json.put("password", password);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
statusCode = response.getStatusLine().getStatusCode();
System.out.println("Status Code=>" + statusCode);
if (statusCode == 200) {
result = EntityUtils.toString(response.getEntity());
Log.v("Login Response", "" + result);
} else {
response = null;
}
}
catch(Exception e){
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
Help me to solve this problem with your best suggestions.
Thanks,
I'm getting stuck with http request using HttpClient that is working fine with 2.2 or 2.3.X versions.
I have a doubt on NetworkOnMainThread Exception.
Look at How to fix android.os.NetworkOnMainThreadException?
Android AsyncTask is the best solution for it.
Update:
Also You are getting 401 error Status Code.
401 means "Unauthorized", so there must be something with your credentials.
Just check the Credential before requesting Web Service.
You're running a network operation on main thread. Use async task to run network operations in background thread. That's why you are getting android.os.NetworkOnMainThreadException.
do it in an async task like this:
class MyTask extends AsyncTask<String, Void, RSSFeed> {
protected void onPreExecute() {
//show a progress dialog to the user or something
}
protected void doInBackground(String... urls) {
//do network stuff
}
protected void onPostExecute() {
//do something post execution here and dismiss the progress dialog
}
}
new MyTask().execute(null);
Here are some tutorials for you if you don't know how to use async tasks:
Tutorial 1
Tutorial 2
Here is official docs

Slow Internet connection leads to force close

I am developing an android application where in each activity i need to pass some data onto the server and get back the responses before going to the next activity. The application works fine if the internet is fast enough. But as the speed goes down the application force closes. How to deal with slow internet connection so that it might not lead to force close of application?????
Here is some part of code
public void onClick(View v) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
if(userFunction.isNetworkAvailable(getApplicationContext()))
{
answer="";
for(int check1=0;check1<counter2;check1++){
int check2=0;
answer=answer+option4[check1]+"|";
while(check2<counter1){
if(edTxt[check1][check2].getText().toString().equals("")){
answer="";
break;
}
else{
answer=answer+edTxt[check1][check2].getText().toString()+"|";
}
check2++;
}
if(answer.equals("")){
break;
}
else{
answer=answer+"||";
}
}
if(answer.equals("")){
Toast.makeText(this, "Please fill all fields", 600).show();
}
else{
userFunction.form1(surveyId,userId , quesNo, answer);
if(total>0){
draw(temp);
}
else{
ques_no++;
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("quesNo", Integer.toString(ques_no)));
params.add(new BasicNameValuePair("surveyId", surveyId));
count = getJsonFromURL22(surveyCond, params);
j=Integer.parseInt(result);
if(j==22)
{
Toast.makeText(this, "Survey Completed", 600).show();
Intent home=new Intent(Format16.this, SurveyCompleted.class);
UserFunctions userFunctions = new UserFunctions();
userFunctions.full(surveyId);
Bundle d=new Bundle();
d.putString("userId", userId);
home.putExtras(d);
startActivity(home);
}
public String getJsonFromURL22(String url, List<NameValuePair> params){
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine());
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
Since you have not shown any code, I am guessing you are targeting Android API level 10 or lower, and you are doing all the networking in the UI thread, resulting in the dreaded App Not Responding(ANR) error. One way to fix the problem would be to use AsyncTask and move all your networking code in there. When done right, AsyncTask's doInBackground() will process all your networking in a separate thread, allowing the UI to remain responsive.
It usually works something like this:
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Do all networking here, this will work away in a background thread.
// In your case:
// HttpResponse response = httpclient.execute(httppost);
// Must happen here
}
#Override
protected void onPostExecute(String result) {
// dismiss progress dialog if any (not required, runs in UI thread)
}
#Override
protected void onPreExecute() {
// show progress dialog if any, and other initialization (not required, runs in UI thread)
}
#Override
protected void onProgressUpdate(Void... values) {
// update progress, and other initialization (not required, runs in UI thread)
}
}
If you enable StrictMode, or target api versions 11 and higher, Android will throw a NetworkOnMainThreadException when you try to do this.
The application works fine if the internet is fast enough. But as the
speed goes down the application force closes.
It clearly indicates that you are doing network operation on UI Thread.As per Google Docs if the Asynchronous operation is performed on Main thread and if it is taking more than 5 seconds then your application will show force close dialog which is very unpleasent for end user.
In-fact if you try to run such application on latest android version (i.e 4.0 or later) It will not allow you to run application it will crash at start as soon as it detects that the asynchronous operation is performed on main thread.
You must use AsyncTask or Handlers to perform long running application.
Go through following blog to know more.
http://android-developers.blogspot.in/2010/07/multithreading-for-performance.html
That must be ANR issue not the Force Close issue.
You can use StrictMode to help find potentially long running operations such as network that you might accidentally be doing your main thread.
Or else try to put progress bar.
use setConnectionTimeout or setSoTimeout for handling connection timeout.
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
and use AsyncTask or Handler or HandlerThread or runOnUiThread anyone for getting data from Server(to perform long running task in background).
You should take a look at this tool that allows you to see what is causing the slow down in your application. The ARO tool is designed to diagnose these sorts of network problems http://developer.att.com/developer/forward.jsp?passedItemId=9700312

it didn't work to connect the android app to servlet page to passing data

i want to connect my android app to my servlet site ,, that i need to pass some data from the app to the url
Can anyone help me?
I have written this code to pass two parameters but it generates an exception:
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/view");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "HAANAA"));
formparams.add(new BasicNameValuePair("id+", "11223"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
it seems that you are blocking the UI thread , and ANR Exception is raised since if your UI Thread is blocked for 5 second this exception will occur , to come over this issue you can use Thread or AsyncTask to do the job ,so your UI thread don't get blocked
example :
public myAsnyc extends AsyncTask<Void, Void,Void>{
protected void doInBackground(){
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/view");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "HAANAA"));
formparams.add(new BasicNameValuePair("id+", "11223"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
}
protected void onPostExecute(){
log.d("myApp", "success");
}
}
and if you want to execute it
make this call
new myAsnyc().execute();
if you want to update the UI elements use the onPostExecute() method and modify the generic type of the async task
UPDATE
execute the following code
use this code
try {
InetAddress i = InetAddress.getByName("http://androidsaveitem.appspot.com/view");
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
before you call the async task
if the exception occur fine , re run the app second time it will run normally

Categories

Resources