将 xml 文件发布到 php 服务器:
public class MainActivity extends AppCompatActivity {
/**
* Send xml file to server via asynchttpclient lib
*/
Button button;
String url = "http://xxx/index.php";
String filePath = Environment.getExternalStorageDirectory()+"/Download/testUpload.xml";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postFile();
}
});
}
public void postFile(){
Log.i("xml","Sending... ");
RequestParams params = new RequestParams();
try {
params.put("key",new File(filePath));
}catch (FileNotFoundException e){
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
Log.i("xml","StatusCode : "+i);
}
@Override
public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
Log.i("xml","Sending failed");
}
@Override
public void onProgress(long bytesWritten, long totalSize) {
Log.i("xml","Progress : "+bytesWritten);
}
});
}
}
将android-async-http-1.4.9.jar添加到android studio后,进入build.gradle并
compile 'com.loopj.android:android-async-http:1.4.9'
在依赖项下添加:
并在 AndroidManifest.xml 添加:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />