Reputation: 1984
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,
Upvotes: 0
Views: 375
Reputation: 109237
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.
Upvotes: 2
Reputation: 20553
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:
Here is official docs
Upvotes: 1