Connect an Android Device To a Web Service on Local Host
Following my previous thread , im now able to connect my Android Device to my local host using wamp
But still i cannot connect to my symfony server and get my API datas
I sarted symfony's internal server :
"Server running on http://127.0.0.1:8000"
I used Internet permission on my AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
My MainActivity.java code
package com.example.cbmedandroid;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.43.13:8000/api/horaire.json");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
When i launch the application and click to the button .
It load during 40 sec and i get this
"Connection to http://192.168.43.13:8000 refused"
192.168.43.13 is my pc adress
What should i do to fix this .
thanks.
FINALLY! i have found the solution to my problem
when running the built-in php server .
We need to specify this command
php bin/console server:run 0.0.0.0:8000
(8000 is my port , you can put yours)
so that Any device or host (ip) could access
if you put 127.0.0.1 only your localhost will be allowed
That's why i couldn't get the Api even i was connected to my localhost via wifi hotspot
It's ok now
Are you able to install this cURL App for Android?
Then use on your Android (is this a real phone or an emulator) open a cURL window and then enter:
cURL http://192.168.43.13:8000/
I tried this same kind of setup with a real Android phone and the above indicated cURL app and put in my Symfony web URL (on another PC), and the Android shows the correct html response back that I'm expecting.
At least this will help you verify functionality first.
Edit below this line:
Here is the code you might use since HttpClient was deprecated:
URL url = new URL("http://192.168.43.13:8000/api/horaire.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestMethod("GET");
// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Not sure if you need to use the "setRequestMethod". But try out this change and see if that works for you.
Related
I wrote the code below to get a simple message from a file php that send me a json object, I have no errors in my code and the PHP code work well, can you please help me to find what is the matter with my code :)
JAVA Code :
package com.example.httpclient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView myListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//This is our textView element
myListView = (TextView) findViewById(R.id.textView1);
//Lets try to connect
try{
//Create a new client object
HttpClient httpclient = new DefaultHttpClient();
//Now post to your demo URL
HttpPost httppost = new HttpPost("http://goldengym.ma/test/test1.php");
//Execute the post and get the response
HttpResponse response = httpclient.execute(httppost);
//Get the message from the response
HttpEntity entity = response.getEntity();
//Get the content of the message
InputStream webs = entity.getContent();
//Convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
//Read one line of the response
myListView.setText(reader.readLine());
//Slow our inputStream
webs.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
}catch (Exception e){
Log.e("log_tag", "Error " + e.toString());
}
}
}
And there is the PHP Code :
<?php
$result = 'TEST WORKED, WE GOT CONNECTION';
print json_encode($result);
?>
And there is my logcat :
03-03 12:35:02.918: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118
03-03 12:35:04.518: W/PackageManager(1995): Code path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk
03-03 12:35:04.518: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118
03-03 12:35:04.518: W/PackageManager(1995): Resource path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk
03-03 12:35:05.218: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118
03-03 12:35:05.493: D/Launcher.LauncherModel(5871): --> package:com.example.httpclient
03-03 12:35:05.723: D/Launcher.LauncherModel(5871): --> update package com.example.httpclient
03-03 12:35:05.723: D/Launcher.LauncherModel(5871): --> package:com.example.httpclient
03-03 12:35:05.913: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient
03-03 12:35:06.188: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REMOVED and uri=com.example.httpclient
03-03 12:35:06.523: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient
03-03 12:35:07.598: W/DeepLinking(3458): no deep link install data found for com.example.httpclient
03-03 12:35:07.663: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_ADDED and uri=com.example.httpclient
03-03 12:35:07.703: D/PackageAddedReceiver(2234): package added com.example.httpclient
03-03 12:35:08.048: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.example.httpclient
package com.example.httpclient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView myListView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//This is our textView element
myListView = (TextView) findViewById(R.id.tv);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//Lets try to connect
try{
//Create a new client object
HttpClient httpclient = new DefaultHttpClient();
//Now post to your demo URL
HttpPost httppost = new HttpPost("http://10.0.2.2/testAndroid/test1.php");
//Execute the post and get the response
HttpResponse response = httpclient.execute(httppost);
//Get the message from the response
HttpEntity entity = response.getEntity();
//Get the content of the message
InputStream webs = entity.getContent();
//Convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
//Read one line of the response
myListView.setText(reader.readLine());
//Slow our inputStream
webs.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
PLz try this code, It is working fine. There should use
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and Manifeast
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.httpclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.provider.testdemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Network calls made on the main Thread are disallowed (http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html)
Also, you need <uses-permission android:name="android.permission.INTERNET"/> in your AndroidManifest.xml file.
Never use Exception to handle your exceptions.
Also, I would try to avoid putting a try-catch into an other try-catch.
do it as follows:
public class MyAsyncTask extends AsyncTask<String, String, String> {
private TextView myListView;
public MyAsyncTask(TextView myListView){
this.myListView = myListView;
}
#Override
protected String doInBackground(String... params) {
String response = null;
HttpClient httpclient = new DefaultHttpClient();
//Now post to your demo URL
HttpPost httppost = new HttpPost(params[0]);
//Execute the post and get the response
HttpResponse response = httpclient.execute(httppost);
//Get the message from the response
HttpEntity entity = response.getEntity();
//Get the content of the message
InputStream webs = entity.getContent();
//Convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
response = reader.readLine();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}finally{
webs.close();
}
return response;
}
#Override
protected void onPostExecute(String result) {
if(result != null){
myListView.setText(result);
}
}
In onCreate() of your activity:
new MyAsyncTask(myListView).execute("http://goldengym.ma/test/test1.php");
The key method of AsyncTask is doInBackground(), which performs the lengthy operations on a separate thread, while onPostExecute works on the main thread. Refer AsyncTask documentation for more detail. Also, before making any call to server, you should always check first, whether internet is available. I had not posted that part here. Hope this helps.
You can not do the internet operations on main thread. It will give you mainThreadException.
You have to use Asynctask for doing these operations. Then only your able to fetch data from the web services.
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
You can use this link to understand how it works.
I am trying to implement http://codify.freebaseapps.com/?request=https%3A%2F%2Fwww.googleapis.com%2Ffreebase%2Fv1%2Fsearch%3Fquery%3DBlue%2BBottle&title=Simple%20Search inside an android application. I have the correct api key installed and matched to the google api service and have imported the appropriate jar files under Referenced Libraries.
My code however keeps throwing a could not find class - 'com.google.api.client.http.javanet.NetHttpTransport' error every time it is run on the emulator. Any suggestions or feedback ?
You must add library into project.
right click project
Properties
Java Build Path
Add External JARs
please read this post: Android and Google client API NetHttptransport Class not found
When I built the Codify app that you linked to I didn't test it against Android so there may be an easier way to do it in Android.
Here's another way to do it using Apache HttpClient and json.org which are included in the Android SDK.
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class FreebaseSearchTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject getJsonContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException, JSONException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
JSONObject jObject = new JSONObject(out.toString());
return jObject;
}
#Override
protected JSONObject doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String query = params[0];
JSONObject result = null;
try {
HttpGet httpGet = new HttpGet("https://www.googleapis.com/freebase/v1/search?query=" + URLEncoder.encode(query, "utf-8"));
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
result = getJsonContentFromEntity(entity);
} catch (Exception e) {
Log.e("error", e.getLocalizedMessage());
}
return result;
}
protected void onPostExecute(JSONObject result) {
doSomething(result);
}
}
I am working on a computer that is joined with server in LAN.proxy is used to access internet in my computer, now i am doing project on consuming php web services which give JSON as output.i have made a app for it but it gives blank response,i have read one of the stack overflow question answer that say that it is because of proxy.
should i have to set proxy setting in my application.
And how can i set proxy for this problem.
i have set the proxy by this step
Click on Menu
Click on Settings
Click on Wireless & Networks
Go to Mobile Networks
Go to Access Point Names
Here you will Telkila Internet, click on it.
In the Edit access point section, input the "proxy" and "port"
Also provide the Username and Password, rest of the fields leave them blank
internet is working in emulator,but still project display nothing.
this is my code
package com.example.jsonexaple2;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class Jsonexaple2 extends Activity {
String archiveQuery = "http://www.archive.org/advancedsearch.php?q=Lotus&fl[]=date&fl[]=format&fl[]=identifier&fl[]=mediatype&fl[]=title&sort[]=createdate+desc&sort[]=&sort[]=&rows=10&page=1&output=json&callback=callback&save=yes";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jsonexaple2);
InputStream in = null;
String queryResult = "";
try {
URL url = new URL(archiveQuery);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while(true){
read = bis.read(buffer);
if(read==-1){
break;
}
baf.append(buffer, 0, read);
}
queryResult = new String(baf.toByteArray());
} catch (MalformedURLException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
} catch (IOException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
}
JSONObject jObject;
try {
jObject = new JSONObject(queryResult.replace("callback(", "")).getJSONObject("response");
JSONArray docsArray = jObject.getJSONArray("docs");
for (int i = 0; i < 10; i++) {
if (docsArray.getJSONObject(i).optString("mediatype").equals("etree")) {
String title = docsArray.getJSONObject(i).optString("title");
String identifier = docsArray.getJSONObject(i).optString("identifier");
String date = docsArray.getJSONObject(i).optString("date");
System.out.println(title + " " + identifier + " " + date);
}
}
} catch (JSONException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
}
}
}
Yes you have to. Once, I had the same problem with the emulator. I searched on Google and I found these two blogs that are nice.
gitshah
twozao
Hope that it will help you.
I'm new to android. My applcation will query to a url and will receive the json response.
But I am unable to fetch the data from the url. I am behind the proxy server ..so have updated the APN settings in the emulator and the built-in browser working fine.
I am using the following code for getting the data...:
package com.android.urlfetch;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class UrlfetchActivity extends Activity {
Button but1;
String result ;
private TextView text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
result = getStringContent("http://www.google.com");
}catch (Exception e) {
// TODO: handle exception
result = "Error";
}
text = (TextView)findViewById(R.id.text);
text.setText(result);
}
url=http://voxpopis.com");
public static String getStringContent(String uri) throws Exception {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(uri));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader (ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
return sb.toString();
}
finally {
}
}
}
I tried to get the anser in stack overflow's similar questions but dint get any answer. Any help will be appreciated.
My logcat response is :
06-30 15:14:08.820: WARN/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 601 uid 10037
06-30 15:14:10.800: WARN/PackageManager(58): Code path for pkg : com.android.urlfetch changing from /data/app/com.android.urlfetch-1.apk to /data/app/com.android.urlfetch-2.apk
06-30 15:14:10.800: WARN/PackageManager(58): Resource path for pkg : com.android.urlfetch changing from /data/app/com.android.urlfetch-1.apk to /data/app/com.android.urlfetch-2.apk
06-30 15:14:12.250: WARN/RecognitionManagerService(58): no available voice recognition services found
06-30 15:14:25.629: WARN/ActivityManager(58): Launch timeout has expired, giving up wake lock!
06-30 15:14:26.257: WARN/ActivityManager(58): Activity idle timeout for HistoryRecord{44fd4af8 com.android.urlfetch/.UrlfetchActivity}
06-30 15:14:36.911: WARN/IInputConnectionWrapper(539): showStatusIcon on inactive InputConnection
This code is working fine in direct connection ....but I am in a proxy network ...its not working in proxy network.What settings I should do to work in a proxy net?
For fetching the data from the web very comfortably you can use Jsoup.To see how to work with this in android with the emulator click here
I have "BackUpContacts.db" database in SQLiteDatabase, it has a table named "ContactInfo" with column names ContactId, ContactName, MobilePhone1, MobilePhone2, OfficePhone1, OfficePhone2, OfficePhone3, HomePhone1, HomePhone2 and TokenId.
What i want is to transfer all data of "ContactInfo" table to the mysql database system at some server (means server has also a table similar to "ContactInfo", where all data of "ContactInfo" will be copied).
The last important thing which i want is that, whenever i want to get contacts(of a specified TokenId) i can backup all those from server to the mobile device in an xml file.
in short, can here anyone help me how to transfer sqlite db to a web server?
One way is to submit data to your webiste's php page by using GET or POST method which will add it to MySql on your remote application server, like
HttpGet request = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpClient client = new DefaultHttpClient();
String response = client.execute(request, responseHandler);
url can be: www.mysite.com?id=5&name=john ...
This also has to be an AsyncTask doInBackground request...
The problem is how many records can be uploaded at once...
It easy to make the remote application server produce an XML file on request to be downloaded by android, with a similar request like above.
This is an example how to upload an XML file from http://w3mentor.com/learn/java/android-development/android-http-services/example-of-multipart-post-using-android/
Where data.xml file and two more fields ("one" and "two") are uploaded to the server. Note that this will require additional jar libraries which you need to download and place in the "lib" folder on the same level as "res" and and "src" folders in the project.
Here are the three jar files you need httpmime-4.0.jar, apache-mime4j-0.6.jar, commons-io-1.4.jar:
http://james.apache.org/download.cgi#Apache_Mime4J
https://repository.apache.org/content/repositories/releases/org/apache/httpcomponents/httpmime/4.0.1/httpmime-4.0.1.jar
http://code.google.com/p/mapmap/downloads/detail?name=commons-io-1.4.jar&can=2&q=
You add this to the project by selecting the project in Exclipse and click File>Properties>Java Build Path>Libraries and then [Add jars]
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
public class TestMultipartPost extends Activity
{
public void executeMultipartPost()throws Exception
{
try {
InputStream is = this.getAssets().open("data.xml");
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://w3mentor.com/Upload.aspx");
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),"uploadedFile");
StringBody sb1 = new StringBody("someTextGoesHere");
StringBody sb2 = new StringBody("someTextGoesHere too");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
} catch (Throwable e)
{
// handle exception here
}
}
}
One more thing, you need to run this in the "background" as an asynchronous task like this:
private class XmlUploadTask extends AsyncTask<Object, String, Boolean> {
private static final String DEBUG_TAG = "XmlUploadTask";
ProgressDialog pleaseWaitDialog;
#Override
protected void onCancelled() {
Log.i(DEBUG_TAG, "onCancelled");
pleaseWaitDialog.dismiss();
}
#Override
protected void onPostExecute(Boolean result) {
Log.i(DEBUG_TAG, "onPostExecute");
pleaseWaitDialog.dismiss();
}
#Override
protected void onPreExecute() {
pleaseWaitDialog = ProgressDialog.show(myActivity.this, "My Application", "Uploading data...", true, true);
pleaseWaitDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
XmlUploadTask.this.cancel(true);
}
});
}
#Override
protected Boolean doInBackground(Object... params) {
//here you enter the xml upload code above
return null;
}
}
Another way which i found over web that how to send xml file to a web server:
For this you need to add a jar file "commons-httpclient.jar" in your project. (How to add jar file is clearly mentioned by ChristianB in above/below post)
You can download this jar file from http://www.java2s.com/Code/Jar/ABC/Downloadcommonshttpclientjar.htm
2.code would be...
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.File;
import java.io.FileInputStream;
class ClassName extends Activity
{
public void Sync(View v) // on button click
{
File xmlFile = new File("sdcard/contacts.xml");
FileInputStream fis = new FileInputStream(xmlFile);
InputStreamRequestEntity isre = new InputStreamRequestEntity(fis);
/*now pass url of server in constructor of PostMethod*/
PostMethod post = new PostMethod("http://w3mentor.com/Upload.aspx");
post.setRequestEntity(isre);
post.setRequestHeader("Content-Type", "text/xml");
HttpClient httpclient = new HttpClient();
int response = httpclient.executeMethod(post);
String res = post.getResponseBodyAsString();
Toast.makeText(GetContacts.this, new Integer(response).toString()+" "+res, Toast.LENGTH_LONG).show();
post.releaseConnection();
}
}