We have an Android and we are sending the database for a Backup to a Web Server to do a backup on the server.
The problem is that the file that the server receives is without extension, and corrupted !
bouton_export.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//ContextWrapper contextWrapper = new ContextWrapper(getBaseContext());
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
File file = new File("data/data/fr.univtours.appelsuaps/databases/Appel.db");
FileBody fileBody = new FileBody(file);
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.quentinlozach.com/get_database.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
HttpResponse response = null;
try {
response = client.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if((response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
// Successfully Uploaded
Log.i("uploaded", response.getStatusLine().toString());
}
else{
// Did not upload. Add your logic here. Maybe you want to retry.
Log.i(" not uploaded", response.getStatusLine().toString());
}
}
}).start();
}
Any idea where it comes from ?
Thanks.
Related
Unfortunately android application has been stopped. At Http Post while attempting to call server at post activity please help
HttpClient cli = new DefaultHttpClient();
//HttpPost post = new HttpPost("http://" + sp.getString("ip", "localhost") + "/attendance/cliLogin.php");
HttpPost post = new HttpPost("localhost/attendance/");
// seting post data
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
String result = EntityUtils.toString(resent);
// reading response
if(result.equals("NoParams"))
Commons.showToast("Something went wrong", true);
else if(result.equals("Login"))
{
navi = new Intent(this, HomeActivity.class);
startActivity(navi);
}
else
Commons.showToast(result, true);
}
catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Commons.showToast("Can't reach server, check the Hostname", true);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
Commons.showToast("Username/Password can't be empty", true);
}
}
Could you please share your logcat to see the error? I think that your are calling the php script in your main thread (that is your activity thread) and you may have NetworkOnMainThreadException
If that is the case:
Create a class that extends the AsyncTask.
Override its methods.
In the creator of this class pass the variables and assign them to the fields (variables) of your class.
Make your post in an AsyncTask inside the doInBackground method
And call the AsyncTask execute. Like this:
public class MyTask extends AsyncTask<String,String,String>{
private short errorType = -1;
private String result;
private String uname;
private String pass;
public MyTask(String uname, String pass){
this.uname = uname;
this.pass = pass;
}
#Override
protected String onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (errorType == 1){
Commons.showToast("Can't reach server, check the Hostname", true);
}
if(result.equals("NoParams")) {
Commons.showToast("Something went wrong", true); }
else if(result.equals("Login")) {
Intent navi = new Intent(this, HomeActivity.class); startActivity(navi);
}
else {
Commons.showToast(result, true);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try
{
HttpClient cli = new DefaultHttpClient();
HttpPost post = new HttpPost("localhost/attendance/");
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
return result = EntityUtils.toString(resent);
}
catch (HttpHostConnectException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
errorType = 1;
return null;
}
catch (ParseException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 2;
return null;
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 3;
return null;
}
catch(Exception e){
errorType = 4;
return null;
}
}
}
And inside the activity make your call like this:
MyTask new MyTask(uname, pass).execute();
Again. All this is applicable only if you have
NetworkOnMainThreadException
Please share your logcat for further help.
Here am using a button to show a gps from one loaction to another...
I am having a problem {Uri.parse("http://maps.google.com/maps?saddr=10.0515097,76.4888416&daddr="+obj.latitude,+obj.longitude));}
while using this...
I am using a web service so latitude and longitude is saved as objects...
I got the gps location without a coma in google map between
+obj.latitude+obj.longitude{Uri.parse("http://maps.google.com/maps?saddr=10.0515097,76.4888416&daddr="+obj.latitude+obj.longitude));}
What should I do to add the comma in between them to track it
Button btn_driver = (Button) v.findViewById(R.id.btn_drivermap);
btn_driver.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("SECOND", "doInBackground()");
HttpEntity resEntity;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Utils.WebserviceUrl + "get_drivers.php?");
MultipartEntity reqEntity = new MultipartEntity();
try {
reqEntity.addPart("user_id", new StringBody(Utils.user_id));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
reqEntity.addPart("latitude", new StringBody(String.valueOf(Utils.geo_latitude)));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reqEntity.addPart("longitude", new StringBody(String.valueOf(Utils.geo_longitude)));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=10.0515097,76.4888416&daddr="+obj.latitude,+obj.longitude));
startActivity(intent);
}});
Just added a plus(+) to it
Uri.parse("http://maps.google.com/maps?saddr=10.0515097,76.4888416&daddr="+obj.latitude+","+obj.longitude));
I know I can link to the Play Store with the URL:
market://details?id=com.example.appname
What I would love to do is 'ping' this URL in the background, and determine if the app is actually available, then, I can modify my UI as appropriate.
Let's assume that, if app is unavailable, the page under http://play.google.com/store/apps/details?id=<package_name> contains, for example, word error-section. If app is available, it does not contain this word.
Make HTTP GET to that URL and search for error-section.
No error-section - your app is available.
Otherwise, it's unavailable.
Like this:
final HttpClient client = new DefaultHttpClient();
final String getURL = "http://play.google.com/store/apps/details?id=<package_name>";
final HttpGet get = new HttpGet(getURL);
final HttpResponse responseGet = client.execute(get);
final HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
final String response = EntityUtils.toString(resEntityGet);
if (response.indexOf("error-section") == -1)
{
// available
}
else
{
// unavailable
}
}
private class URLTest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
try {
HttpClient httpclient = new DefaultHttpClient();
String strurl = "https://play.google.com/store/apps/details?id=com.rovio.angrybirdsstarwars.ads.iap";
// String strurl =
// "https://play.google.com/store/apps/details?id=com.rovio.angrybirdsstarwars.ads.iaptest";
// //fake packagename append with "test"
HttpGet httpget = new HttpGet(strurl);
HttpResponse httpresp = httpclient.execute(httpget);
if (httpresp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Log.e("Found", "YES");
} else if (httpresp.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
Log.e("Found", "NO");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
Log.e("", "");
}
return null;
}
}
i tried with correct & fake packages and its giving bad request responze if the app not available & positive(success 200 code) if app is there..so plz check it once it might help u.
android 2.2 & app min req 2.3
iused:
private void postFile() {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(ConstValue.SEARCH_BY_PICTER);
File file = new File(currentPath);
ContentBody cbFile = new FileBody(file, "image/jpeg");
MultipartEntity mpEntity = new MultipartEntity();
try {
mpEntity.addPart("fileToUpload", cbFile);
mpEntity.addPart("sys", new StringBody("android"));
mpEntity.addPart("ver", new StringBody(ConstValue.VERSION_NAME));
mpEntity.addPart("cid", new StringBody(cid));
mpEntity.addPart("page", new StringBody("1"));
mpEntity.addPart("offset", new StringBody("80"));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
httppost.setEntity(mpEntity);
// System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpEntity resEntity = response.getEntity();
// System.out.println(response.getStatusLine());
if (resEntity != null) {
try {
final String response_str = EntityUtils.toString(resEntity);
if (!response_str.contains("####")) {
ConstValue.goodByPiclist = GoodXMLUtil.parseResponse(response_str);
} else {
Toast.makeText(context, "sorry,server is busy", 2000).show();
}
// Log.d("log", response_str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resEntity != null) {
try {
resEntity.consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
httpclient.getConnectionManager().shutdown();
}
i used jar is httpmime-4.1.2.jar,the code is very well in android and other phone.but in samsung is9023 not run,if my code have mistake,if yes can you give me some advice or some good other method.very very thank you
edit: sorry i have solved the problem ,my code is right,and samsung is good,my mistake is i put image size is not valid
edit:i have meet new problem,in samsung only upload Pure color succeed as Pure white,Pure Black.other htc android phone any color ie very well.if samsung is9023 not trust httpmime-4.1.2.jar very well.because in php not receive any data if i used other pic in samsung
one possibilty can be that currentPath is hard coded like ../sdcard/ and as every device have diffrent external storage location so use Environment.getExternalDirectory() instead .
I'm trying to use HttpClient to connect to a php page that logs in and passes back a sessionid and then goes to a new page, using that sessionid and obtains a mySQL datafield associated with that sessionid.
On the first request, HttpClient can take 1.5 seconds, 6 seconds, or 2 minutes. If the first request was slow, subsequence requests seem to be faster, and visaversa.
The HttpClient request occurs when a Button view is clicked
Here's my code:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
name = (TextView)findViewById(R.id.name);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.pass);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(this);
HttpParams params1 = new BasicHttpParams();
params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client = new DefaultHttpClient(params1);
httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Create local HTTP context
}
public void onClick(View v) {
if (v.getId() == R.id.button1) {
//submit.setClickable(false);
String username = user.getText().toString();
String password = pass.getText().toString();
String targetURL = "<<<<LOGIN PHP URL>>>>";
post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("params","params added");
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("entity added","entityadded");
Log.d("preex","PRE EXECUTION");
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//submit.setText("Logging In...");
new Thread(new Runnable(){
public void run(){
try {
Log.d("pre","pre execute");
response = client.execute(post,localContext);
Log.d("post","post execute");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("response: ",convertStreamToString(input));
getFullName(localContext);
}
}
}).start();}
}
private void getFullName(final HttpContext context){
Log.d("called","called");
String targetURL = "<<<<SESSION CHECKER PHP URL>>>>";
//client1 = new DefaultHttpClient();
post1 = new HttpPost(targetURL);
Log.d("","about to call runable....");
// submit.setText("Obtaining Full Name...");
try {
Log.d("pre","CALLING!");
response = client.execute(post1,context);
Log.d("post","called..");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
//submit.setText("Full Name Obtained!...");
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("response: ",convertStreamToString(input));
outputResponse(input);
}
}
private void outputResponse(final InputStream in) {
name.post(new Runnable(){
public void run(){
String fullname=convertStreamToString(in);
name.setText("Full Name is: "+fullname);
}
});
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Before I set Http version 1.1 it took double the time, but for my application, the speed cannot be unreliable. This is all on a pretty fast WiFi connections -- can you image Edge or 3G speeds??
So what can I optimize?
Thanks everyone:)
EDIT: I did a new test with: http://www.posttestserver.com/ and it happened pretty fast. The urls I'm using currently aren't my final server urls, they are for a different site on a different server -- shared hosting, so could it be that contacting my shared hosting site is just slow and will be compared to my .net server?
Thanks again !