2023-05-12 开启多语言插件支持……

Android 上传图片 请求php接口

android 苏 demo 3733℃ 0评论

php代码:

  1. "1", "message" => $_FILES ['uploadfile'] ['name'] );
  2. echo json_encode ( $array );
  3. } else {
  4. $array = array ("code" => "0", "message" => "There was an error uploading the file, please try again!" . $_FILES ['uploadfile'] ['error'] );
  5. echo json_encode ( $array );
  6. }
  7. ?>

java代码示例一:

  1. package com.example.fileupload;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.net.HttpURLConnection;
  12. import java.net.URL;
  13.  
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.HttpVersion;
  17. import org.apache.http.client.ClientProtocolException;
  18. import org.apache.http.client.HttpClient;
  19. import org.apache.http.client.methods.HttpPost;
  20. import org.apache.http.entity.mime.MultipartEntity;
  21. import org.apache.http.entity.mime.content.FileBody;
  22. import org.apache.http.impl.client.DefaultHttpClient;
  23. import org.apache.http.params.CoreProtocolPNames;
  24. import org.apache.http.util.EntityUtils;
  25.  
  26. import android.app.Activity;
  27. import android.os.Bundle;
  28. import android.util.Log;
  29. import android.view.View;
  30. import android.view.View.OnClickListener;
  31. import android.widget.Button;
  32.  
  33. import com.loopj.android.http.AsyncHttpClient;
  34. import com.loopj.android.http.AsyncHttpResponseHandler;
  35. import com.loopj.android.http.RequestParams;
  36.  
  37. /**
  38. *
  39. * ClassName:UploadActivity Function: TODO 测试上传文件,PHP服务器端接收 Reason: TODO ADD
  40. * REASON
  41. *
  42. * @author Jerome Song
  43. * @version
  44. * @since Ver 1.1
  45. * @Date 2013 2013-4-20 上午8:53:44
  46. *
  47. * @see
  48. */
  49. public class UploadActivity extends Activity implements OnClickListener {
  50. private final String TAG = "UploadActivity";
  51.  
  52. private static final String path = "/mnt/sdcard/Desert.jpg";
  53. private String uploadUrl = "http://192.168.1.102:8080/Android/testupload.php";
  54. private Button btnAsync, btnHttpClient, btnCommonPost;
  55. private AsyncHttpClient client;
  56.  
  57. @Override
  58. protected void onCreate(Bundle savedInstanceState) {
  59. super.onCreate(savedInstanceState);
  60. setContentView(R.layout.activity_upload);
  61. initView();
  62. client = new AsyncHttpClient();
  63. }
  64.  
  65. private void initView() {
  66. btnCommonPost = (Button) findViewById(R.id.button1);
  67. btnHttpClient = (Button) findViewById(R.id.button2);
  68. btnAsync = (Button) findViewById(R.id.button3);
  69. btnCommonPost.setOnClickListener(this);
  70. btnHttpClient.setOnClickListener(this);
  71. btnAsync.setOnClickListener(this);
  72. }
  73.  
  74. @Override
  75. public void onClick(View v) {
  76. long startTime = System.currentTimeMillis();
  77. String tag = null;
  78. try {
  79. switch (v.getId()) {
  80. case R.id.button1:
  81. upLoadByCommonPost();
  82. tag = "CommonPost====>";
  83. break;
  84. case R.id.button2:
  85. upLoadByHttpClient4();
  86. tag = "HttpClient====>";
  87. break;
  88. case R.id.button3:
  89. upLoadByAsyncHttpClient();
  90. tag = "AsyncHttpClient====>";
  91. break;
  92. default:
  93. break;
  94. }
  95. } catch (Exception e) {
  96. e.printStackTrace();
  97.  
  98. }
  99. Log.i(TAG, tag + "wasteTime = "
  100. + (System.currentTimeMillis() - startTime));
  101. }
  102.  
  103. /**
  104. * upLoadByAsyncHttpClient:由人造post上传
  105. *
  106. * @return void
  107. * @throws IOException
  108. * @throws
  109. * @since CodingExample Ver 1.1
  110. */
  111. private void upLoadByCommonPost() throws IOException {
  112. String end = "\r\n";
  113. String twoHyphens = "--";
  114. String boundary = "******";
  115. URL url = new URL(uploadUrl);
  116. HttpURLConnection httpURLConnection = (HttpURLConnection) url
  117. .openConnection();
  118. httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
  119. // 允许输入输出流
  120. httpURLConnection.setDoInput(true);
  121. httpURLConnection.setDoOutput(true);
  122. httpURLConnection.setUseCaches(false);
  123. // 使用POST方法
  124. httpURLConnection.setRequestMethod("POST");
  125. httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
  126. httpURLConnection.setRequestProperty("Charset", "UTF-8");
  127. httpURLConnection.setRequestProperty("Content-Type",
  128. "multipart/form-data;boundary=" + boundary);
  129.  
  130. DataOutputStream dos = new DataOutputStream(
  131. httpURLConnection.getOutputStream());
  132. dos.writeBytes(twoHyphens + boundary + end);
  133. dos.writeBytes("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
  134. + path.substring(path.lastIndexOf("/") + 1) + "\"" + end);
  135. dos.writeBytes(end);
  136.  
  137. FileInputStream fis = new FileInputStream(path);
  138. byte[] buffer = new byte[8192]; // 8k
  139. int count = 0;
  140. // 读取文件
  141. while ((count = fis.read(buffer)) != -1) {
  142. dos.write(buffer, 0, count);
  143. }
  144. fis.close();
  145. dos.writeBytes(end);
  146. dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
  147. dos.flush();
  148. InputStream is = httpURLConnection.getInputStream();
  149. InputStreamReader isr = new InputStreamReader(is, "utf-8");
  150. BufferedReader br = new BufferedReader(isr);
  151. String result = br.readLine();
  152. Log.i(TAG, result);
  153. dos.close();
  154. is.close();
  155. }
  156.  
  157. /**
  158. * upLoadByAsyncHttpClient:由HttpClient4上传
  159. *
  160. * @return void
  161. * @throws IOException
  162. * @throws ClientProtocolException
  163. * @throws
  164. * @since CodingExample Ver 1.1
  165. */
  166. private void upLoadByHttpClient4() throws ClientProtocolException,
  167. IOException {
  168. HttpClient httpclient = new DefaultHttpClient();
  169. httpclient.getParams().setParameter(
  170. CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
  171. HttpPost httppost = new HttpPost(uploadUrl);
  172. File file = new File(path);
  173. MultipartEntity entity = new MultipartEntity();
  174. FileBody fileBody = new FileBody(file);
  175. entity.addPart("uploadfile", fileBody);
  176. httppost.setEntity(entity);
  177. HttpResponse response = httpclient.execute(httppost);
  178. HttpEntity resEntity = response.getEntity();
  179. if (resEntity != null) {
  180. Log.i(TAG, EntityUtils.toString(resEntity));
  181. }
  182. if (resEntity != null) {
  183. resEntity.consumeContent();
  184. }
  185. httpclient.getConnectionManager().shutdown();
  186. }
  187.  
  188. /**
  189. * upLoadByAsyncHttpClient:由AsyncHttpClient框架上传
  190. *
  191. * @return void
  192. * @throws FileNotFoundException
  193. * @throws
  194. * @since CodingExample Ver 1.1
  195. */
  196. private void upLoadByAsyncHttpClient() throws FileNotFoundException {
  197. RequestParams params = new RequestParams();
  198. params.put("uploadfile", new File(path));
  199. client.post(uploadUrl, params, new AsyncHttpResponseHandler() {
  200. @Override
  201. public void onSuccess(int arg0, String arg1) {
  202. super.onSuccess(arg0, arg1);
  203. Log.i(TAG, arg1);
  204. }
  205. });
  206. }
  207.  
  208. }
  209.  

appache提供给的httpclient4

  1. /**
  2. * Post方法传送文件和消息
  3. *
  4. * @param url 连接的URL
  5. * @param queryString 请求参数串
  6. * @param files 上传的文件列表
  7. * @return 服务器返回的信息
  8. * @throws Exception
  9. */
  10. public String httpPostWithFile(String url, String queryString, List files) throws Exception {
  11. String responseData = null;
  12. URI tmpUri=new URI(url);
  13. URI uri = URIUtils.createURI(tmpUri.getScheme(), tmpUri.getHost(), tmpUri.getPort(), tmpUri.getPath(),
  14. queryString, null);
  15. Log.i(TAG, "QHttpClient httpPostWithFile [1] uri = "+uri.toURL());
  16. MultipartEntity mpEntity = new MultipartEntity();
  17. HttpPost httpPost = new HttpPost(uri);
  18. StringBody stringBody;
  19. FileBody fileBody;
  20. File targetFile;
  21. String filePath;
  22. FormBodyPart fbp;
  23. List queryParamList=QStrOperate.getQueryParamsList(queryString);
  24. for(NameValuePair queryParam:queryParamList){
  25. stringBody=new StringBody(queryParam.getValue(),Charset.forName("UTF-8"));
  26. fbp= new FormBodyPart(queryParam.getName(), stringBody);
  27. mpEntity.addPart(fbp);
  28. // Log.i(TAG, "------- "+queryParam.getName()+" = "+queryParam.getValue());
  29. }
  30. for (NameValuePair param : files) {
  31. filePath = param.getValue();
  32. targetFile= new File(filePath);
  33. fileBody = new FileBody(targetFile,"application/octet-stream");
  34. fbp= new FormBodyPart(param.getName(), fileBody);
  35. mpEntity.addPart(fbp);
  36. }
  37. // Log.i(TAG, "---------- Entity Content Type = "+mpEntity.getContentType());
  38. httpPost.setEntity(mpEntity);
  39. try {
  40. HttpResponse response=httpClient.execute(httpPost);
  41. Log.i(TAG, "QHttpClient httpPostWithFile [2] StatusLine = "+response.getStatusLine());
  42. responseData =EntityUtils.toString(response.getEntity());
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }finally{
  46. httpPost.abort();
  47. }
  48. Log.i(TAG, "QHttpClient httpPostWithFile [3] responseData = "+responseData);
  49. return responseData;
  50. }

结果监测:
1366423700_3317

打赏

转载请注明:苏demo的别样人生 » Android 上传图片 请求php接口

   如果本篇文章对您有帮助,欢迎向博主进行赞助,赞助时请写上您的用户名。
支付宝直接捐助帐号oracle_lee@qq.com 感谢支持!
喜欢 (0)or分享 (0)
收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!
按钮 内容不能为空!
立刻说两句吧! 查看0条评论