【发布时间】:2016-01-18 18:13:50
【问题描述】:
这是我的代码。但是我的服务器没有得到正确的数据 我正在尝试通过 httpclient 发送文件 我还读到 http 客户端在 6.0 之后被弃用 那我应该改用什么方法 并且可以发布他们的工作/运行代码 我可以通过我的 android 手机将我的 word/pdf/text 文件发送到 php 服务器
package com.example.sendfiletoserver;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class SendFileToServer extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_file_to_server);
new postFileAsync().execute();
}
private void uploadFile() throws ClientProtocolException, IOException {
String file=Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.pdf";
Log.d("Mayur", ""+file);
HttpClient httpclient=new DefaultHttpClient();
HttpPost post=new HttpPost("<My_address>"); //My server address
File f=new File(file);
FileBody filebody=new FileBody(f);
MultipartEntity mentity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mentity.addPart("file", filebody);
post.setEntity(mentity);
HttpResponse responce=httpclient.execute(post);
HttpEntity entity=responce.getEntity();
}
public class postFileAsync extends AsyncTask<Void, Void, Void> {
// ProgressDialog pd;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// pd = new ProgressDialog(SendFileToServer.this);
// pd.setCancelable(false);
// pd.setMessage("Uploading File");
// pd.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
uploadFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// pd.dismiss();
}
}
}
这是我的 php 代码
<?php
// if text data was posted
if ($_POST) {
print_r($_POST);
}
// if a file was posted
else if ($_FILES) {
$file = $_FILES['file'];
$fileContents = file_get_contents($file["tmp_name"]);
print_r($fileContents);
}
?>
我对php一无所知 所以如果有人可以给我php代码来帮助我。我什至不知道我的代码是否正确
提前谢谢你
【问题讨论】:
标签: php android http pdf server