I want to know why does this code not execute? I'm trying to send my data from my device via POST method but there is no error. The app just finishes by itself on my device by communicating "My app was stopped.:
Here is execution:
KlientNameValue kn = new KlientNameValue(getApplicationContext());
kn.new MyAsyncTask().execute(zam.klient.getNazwa(),zam.klient.getNip(),zam.klient.getAdres());
And here is code:
public class KlientNameValue {
List<NameValuePair> KlientNameValuePairs = new ArrayList<NameValuePair>();
Context context;
public KlientNameValue(Context context) {
super();
this.context=context;
}
public class MyAsyncTask extends AsyncTask<String, Void, Void> {
#Override protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0], params[1], params[2]);
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(context , "Zlecenie zostało wysłane",
Toast.LENGTH_LONG).show();
}
void postData(String nazwa, String nip, String adres) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("here is my default link :)");
try { // Add your data
KlientNameValuePairs = new ArrayList<NameValuePair>();
KlientNameValuePairs.add(new BasicNameValuePair("Kli_imie", nazwa));
KlientNameValuePairs.add(new BasicNameValuePair("Kli_adres", adres));
KlientNameValuePairs.add(new BasicNameValuePair( "Kli_nr_telefonu",
nip));
httppost.setEntity(new UrlEncodedFormEntity( KlientNameValuePairs));
HttpResponse response = httpclient.execute(httppost);
//httppost.setEntity(new UrlEncodedFormEntity(
// ZamowienieNameValuePairs)); // HttpResponse response1 =
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); }
}
}
}
Error:
02-15 17:45:24.695: E/AndroidRuntime(21890): at android.widget.Toast.<init>(Toast.java:94)
02-15 17:47:19.343: W/SingleClientConnManager(22288): Invalid use of SingleClientConnManager: connection still allocated.
02-15 17:47:19.343: W/SingleClientConnManager(22288): Make sure to release the connection before allocating another one.
Invalid use of SingleClientConnManager: connection still allocated.
You are executing the http request two times that is completely wrong before you consume it. So remove the second httpclient.execute(httppost); because you have already execute this http request.
and call this
httpResponse.getEntity().consumeContent();
Above method is called to indicate that the content of this entity is no longer required. All entity implementations are expected to release all allocated resources as a result of this method invocation
public static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(
new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
use this code so that your exception of free resource and allocate or being used will not come
This exception can happen when two or more threads interact with a single org.apache.http.impl.client.DefaultHttpClient
or simply give new object to each request when and where ever you are calling you get or post http client request to interact with server to fetch the data or download the large file
like
String post_url="http://www.google.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(Post_url);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = client.execute(httpost);
String response= EntityUtils.toString(httpResponse.getEntity());
as you like in code to retrieve the response
Related
I am writing an Android application in Android Studio which is sending a POST request to the server.
I have made a class for the HTTP connection:
public class PostTask extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
Requester requester = new Requester();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://dev-api.shping.com/serialization-service/reassignment/task");
HttpResponse response = null;
HttpHost httpproxy = new HttpHost("hmkproxy1.fmlogistic.fr",8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpproxy);
try {
httppost.setHeader("authenticateit_identity_ticket","63eb8926-e661-42c1-998d-3f008665c8e5");
httppost.setHeader("cache-control","no-cache");
httppost.setHeader("content-type", "application/json");
StringEntity params = new StringEntity(requester.getJsonObject().toString());
httppost.setEntity(params);
// Execute HTTP Post Request
response = httpclient.execute(httppost);
System.out.println(response);
} catch (ClientProtocolException e) {
System.out.println("FUCK1");
} catch (IOException e) {
System.out.println(e);
}
return null;
}
}
I am connecting through a proxy. I get this exception while my app works: java.net.SocketException: java.lang.IllegalStateException: No factory found
Please help me, there is nearly no information about this exception on the internet. I tried to add some socket factories to my method, but it doesn't seems to work so I deleted them.
Thanks!
Remove android:networkSecurityConfig from manifest.
How to send value to php page using Asynchronous with HttpRequest and get a response, then do something with it using OnPostExcute for example.
Java :
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
// Do something with the response here
// ....
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
}
PHP :
<?php
// return the value back to the app
echo $_POST["myHttpData"];
?>
private class MyAsyncTask extends AsyncTask<String, HttpResponse, HttpResponse>{
#Override
protected HttpResponse doInBackground(String... params) {
// TODO Auto-generated method stub
return postData(params[0]);
}
protected void onPostExecute(HttpResponse result){
View pb;
pb.setVisibility(View.GONE);
HttpEntity entity = result.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(mContext, responseString, Toast.LENGTH_LONG).show();
}
#SuppressWarnings("unchecked")
public HttpResponse postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return response;
}
}
You could do something with the above. That would certainly pass the HttpResponse to the onPostExecute method and allow you to do something with it.
I'd take a look at this line, though:
httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));
As it didn't seem right to me. I had to add the cast to make the compiler happy. That may not be the desired result (but the point wast to get the ASyncTask to allow for processing the HttpResponse).
I want to know that if a doInBackground method of a AsyncTask calls a method, for example XYZ(), Is that method also executed asynchronously?
Can we make changes to the UI in XYZ() in such a situation? Will it make the UI unresponsive?
I have a method call in doInBackground which is network intensive and requires to download an image from the web. The UI becomes unresponsive as soon as the call to that method is made. Why?
protected String[] doInBackground(String... params)
{
String[] response = new String[2];
Log.v("Background", "I am in background!");
String url = params[0];
String VoiceInput = params[1];
IsCalledOnVoiceInput = VoiceInput;
Log.v(url,url);
HttpPost httppost = new HttpPost(url);
try
{
HttpParams p = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(p);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseBody = httpclient.execute(httppost,
responseHandler);
Log.v("Thread", responseBody);
//Getting background image URL
JSONObject reader = new JSONObject(responseBody);
JSONObject coords = reader.getJSONObject("coord");
loc_latitude = coords.getString("lat");
loc_longitude = coords.getString("lon");
String imageURL="";
/////////////////////////////////////////////////////////////////////////////////
try
{
imageURL = getRandomImageURL(loc_latitude,loc_longitude);
Log.v("Image URL as recieved from getRandomImageURL", imageURL);
//Trying to convert Image from the above URL, get it and theh convert it to String
URL urlOfTheImage = new URL(imageURL);
bmp = BitmapFactory.decodeStream(urlOfTheImage.openConnection().getInputStream());
//Image successfully converted to string, ready to pass as a parameter!
response[0] = "";
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"There seems to be a problem with the application. Please try again later.", Toast.LENGTH_LONG).show();
}
Log.v("URL of Random Image",imageURL);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
response[1] = responseBody;
return response;
}
The method getRandomImageURL and all that code in the try block is network intensive. I can also provide its code.
The code executing in the background is run in a separate thread. Anything it does, including calling other methods, happens in that thread. Since this is not the UI thread, it's not valid to make UI calls. You have to post messages to the UI thread.
Yes, whatever you call within doInBackgroud will run asynchronously. And no you shoudn't update UI from background thread for that you have CallBackDefined(onPostExecute). Or if UI update is require you can use runOnUIThread(...) API
You can make changes to the UI only from the UI thread. In general the doInBackground() is for lengthy operations that do not update the UI or access the UI toolkit. You can periodically publish changes in state that need to be reflected in the UI (eg progress bar showing status of a download operation) by calling publishProgress().
Set time out like this...
HttpPost httppost = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httppost);
I am using an asynchronous post method to post some data to the server. The post is working fine, but if the server is down or unresponsive then I am getting a force close in the application.
How should I implement a timeout to the post request?
This is the class which is asynchronously posting to a particular url:
//===================================================================================================================================
//sending EmailAddress and Password to server
//===================================================================================================================================
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0],params[1]);
return null;
}
protected void onPostExecute(Double result){
if(responseBody.contains("TRUE"))
{
String raw=responseBody;
raw = raw.substring(0, raw.lastIndexOf("<"));
raw = raw.substring(raw.lastIndexOf(">") + 1, raw.length());
String [] contents = raw.split(",");
//extracting user name and user id from response
String user_name=contents[1];
String student_code=contents[2];
//save user name and user id in preference
saveInPreference("user_name",user_name);
saveInPreference("student_code",student_code);
//login is successful, going to next activity
Intent intent = new Intent(LoginActivity.this, TakeTestActivity.class);
//hiding progress bar
progress.dismiss();
finish();
LoginActivity.this.startActivity(intent);
}
else
{
//hiding progress bar
progress.dismiss();
create_alert("Attention!", "Please provide valid userid and password");
}
}
protected void onProgressUpdate(Integer... progress){
}
public void postData(String emailId,String passwrd) {
**//EDIT START**
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient(httpParams);
**//EDIT END**
// Create a new HttpClient and Post Header
//HttpClient httpclient = new DefaultHttpClient();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
final String url_first = preferences.getString("URLFirstPart","");
HttpPost httppost = new HttpPost(url_first+"ValidateLogin");
try {
// Data that I am sending
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("EmailId", emailId));
nameValuePairs.add(new BasicNameValuePair("Password", passwrd));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
**//EDIT START**
try
{
// Execute HTTP Post Request
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
}
catch (SocketTimeoutException ex)
{
// Do something specific for SocketTimeoutException.
}
**//EDIT END**
//Log.d("result", responseBody);
}
catch (Throwable t ) {
}
}
}
//===================================================================================================================================
//END sending EmailAddress and Password to server
//===================================================================================================================================
This is how I am calling the class to execute the post request:
//sending request for login
new MyAsyncTask().execute(txtUsername.getText().toString(),txtPassword.getText().toString());
What should I do to implement a connection timeout after a particular time if the server does not respond or is not available?
Edited:
How do I notify the user using an alert that the connection has timed out? Where should I put the alert and during which condition?
Thanks in advance!
You can try this, I've set 10 sec. here...
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
I have been trying to get my Android App to post data to a PHP file, which then writes that data to a database, however I'm having a bit of trouble with it.
I'm getting this error, however it's not force closing or anything.
Logcat Output:
08-13 20:29:42.859: I/postData(11950): HTTP/1.1 200 OK
08-13 20:29:42.859: E/log_tag(11950): Error in http connectionjava.lang.IllegalStateException: Content has been consumed
Here is the code in question that's doing all my HTTP POST stuff, the android side of things:
SubmitWord task = new SubmitWord();
task.execute(new String[] { "http://www.hanged.comli.com/main.php" });
The above code calls this asynchronous task:
private class SubmitWord extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
String response = "";
try
{
URL = urls[0];
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("victim",myId));
nameValuePairs.add(new BasicNameValuePair("rival",newname));
nameValuePairs.add(new BasicNameValuePair("word","HELLOHOMO"));
nameValuePairs.add(new BasicNameValuePair("won","0"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
HttpEntity entity = execute.getEntity();
InputStream is = entity.getContent();
Log.i("postData", execute.getStatusLine().toString());
//HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result)
{
mText.setText("DONE");
}
}
Here is the PHP side of things:
<?php
/// REMOVED DATABASE DETAILS
$connect = mysql_connect("$mysql_host", "$mysql_user", "$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database", $connect)or die("cannot select DB");
session_start();
$victim = $_POST['victim'];
$rival = $_POST['rival'];
$word = $_POST['word'];
$won = $_POST['won'];
mysql_query("INSERT INTO currentgames (victim, rival, wordguess, won) VALUES('$victim', '$rival', '$word', '$won'))");
I'm fairly sure it's just the Java/Android part that I've gotten wrong, but I can't figure out for the life of me what I'm doing wrong, I have tried various different methods of POSTING data and read a number of tutorials on using HTTPOST. Maybe I'm just not understanding correctly.
The culprit is you are calling getContent(); twice.
As per javadoc
Returns a content stream of the entity. Repeatable entities are expected to create a new instance of InputStream for each invocation of this method and therefore can be consumed multiple times. Entities that are not repeatable are expected to return the same InputStream instance and therefore may not be consumed more than once.