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
Related
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.
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.
Hi I'm about to perform an HTTP request to add some data to a local data base using wampserver, so I've made a button andh within that button i will perform that action , but the problem is that i can't connect to the data base !!!
this is the message apperas on the toast "android.os.networkonmainthreadexception"
and this is my code ---> http://pastebin.com/TsQ7NbNm
============================
I'm Newer to Android Programming so please Help me !
You cannot make http request on your UI thread. Consider using AsyncTask or some other method of asynchronuos call.
Upto the API level-10 it is fine to make http request on UI thread. But from API-11, any task that takes long time to complete must be done on background task. The reason behind this is any task that takes 5 seconds or more on UI thread then ANR(Application Not Responding) i.e. force close happens. To do that we have create some background thread or simply make use of AsyncTask.
if you want to post data on your server then you need to well design server for post data. recent my server configuration i post data by using this code and well performed.
Button send = (Button) findViewById(R.id.send_sms);
send.setOnClickListener(this);
public void onClick(View v)
{
switch (v.getId())
{
case R.id.send_sms:
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://10.0.2.2/folder/saver.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cell", "+8801899999"));
params.add(new BasicNameValuePair("pin", "1234"));
params.add(new BasicNameValuePair("msg", "hi!"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
showAlert(EntityUtils.toString(resEntity));
//Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
you can try this way.if your server has password then give it.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$valeur1=$_REQUEST['valeur1'];
$valeur2=$_REQUEST['valeur2'];
$req=mysql_query("insert into testapp (valeur1,valeur2) values('$valeur1','$valeur2')");
if($req)
echo "ok";
else
echo "erreur";
;
?>
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
I'm trying to cancel my AsyncTask when connecting to the server fails. I tried cancel(), but the onPostExecute() method still gets called, instead of onCancelled().
This is what I have inside doInBackground():
protected String doInBackground(String... params) {
Log.i("ping", "doInBackground() started");
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpResponse response;
HttpEntity entity;
try {
HttpPost post = new HttpPost("http://192.168.1.6/ping/login.php");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", getEmail()));
nvps.add(new BasicNameValuePair("password", getPassword()));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = client.execute(post);
entity = response.getEntity();
InputStream iStream = entity.getContent();
read(iStream);
iStream.close();
if(entity != null)
entity.consumeContent();
Log.i("ping", "doInBackground() vervolgd");
} catch (Exception e) {
e.printStackTrace();
Log.e("tvsping", "Exception: " + e.getMessage());
cancel(true);
}
return null;
}
I'm trying to see what happens when the server can't be reached (I'm shutting it down, so there's no way my phone is getting any response) and I get IOException: the connection was reset.
Any ideas how I should check if the connection isn't made?
update
I solved this like Tanmay suggested, with a boolean. But I have another problem:
Every time doInBackground() is called it takes about three minutes to stop, when it can't find the servers. Everything is fine when it can reach the server, but I can't have this taking 3 minutes before the user is notified of anything (I could do a background process, but still a 3 minute wating bar is no good neither)
Any ideas what is wrong with my code? This can't be normal, right?
From doInBackground() method you are returning a String .You can return null if your HTTPPost fails.And then in onPostExecute() method just check what are you getting, if the String is null dont do anything which you really want and on successful running do your UI work
Hope this will help you.
HttpHost target = new HttpHost("192.168.2.3", 80);
HttpPost post = new HttpPost("/ping/login.php");
response = client.execute(target, post);
This solved the slow server response for me.