热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

Android通过HTTP协议实现上传文件数据

这篇文章主要为大家详细介绍了Android通过HTTP协议实现上传文件数据,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android通过HTTP协议实现上传文件数据的具体代码,供大家参考,具体内容如下

SocketHttpRequester.java

package cn.itcast.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class SocketHttpRequester {
 /**
 * 发送xml数据
 * @param path 请求地址
 * @param xml xml数据
 * @param encoding 编码
 * @return
 * @throws Exception
 */
 public static byte[] postXml(String path, String xml, String encoding) throws Exception{
 byte[] data = xml.getBytes(encoding);
 URL url = new URL(path);
 HttpURLConnection cOnn= (HttpURLConnection)url.openConnection();
 conn.setRequestMethod("POST");
 conn.setDoOutput(true);
 conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
 conn.setRequestProperty("Content-Length", String.valueOf(data.length));
 conn.setConnectTimeout(5 * 1000);
 OutputStream outStream = conn.getOutputStream();
 outStream.write(data);
 outStream.flush();
 outStream.close();
 if(conn.getResponseCode()==200){
  return readStream(conn.getInputStream());
 }
 return null;
 }
 
 /**
 * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
 *  
  
  
  
   
  
 * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
 * @param params 请求参数 key为参数名,value为参数值
 * @param file 上传文件
 */
 public static boolean post(String path, Map params, FormFile[] files) throws Exception{   
    final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
    final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志
    
    int fileDataLength = 0;
    for(FormFile uploadFile : files){//得到文件类型数据的总长度
     StringBuilder fileExplain = new StringBuilder();
     fileExplain.append("--");
     fileExplain.append(BOUNDARY);
     fileExplain.append("\r\n");
     fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
     fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
     fileExplain.append("\r\n");
     fileDataLength += fileExplain.length();
     if(uploadFile.getInStream()!=null){
     fileDataLength += uploadFile.getFile().length();
    }else{
    fileDataLength += uploadFile.getData().length;
    }
    }
    StringBuilder textEntity = new StringBuilder();
    for (Map.Entry entry : params.entrySet()) {//构造文本类型参数的实体数据
      textEntity.append("--");
      textEntity.append(BOUNDARY);
      textEntity.append("\r\n");
      textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
      textEntity.append(entry.getValue());
      textEntity.append("\r\n");
    }
    //计算传输给服务器的实体数据总长度
    int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
    
    URL url = new URL(path);
    int port = url.getPort()==-1 ? 80 : url.getPort();
    Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);    
    OutputStream outStream = socket.getOutputStream();
    //下面完成HTTP请求头的发送
    String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
    outStream.write(requestmethod.getBytes());
    String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
    outStream.write(accept.getBytes());
    String language = "Accept-Language: zh-CN\r\n";
    outStream.write(language.getBytes());
    String cOntenttype= "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
    outStream.write(contenttype.getBytes());
    String cOntentlength= "Content-Length: "+ dataLength + "\r\n";
    outStream.write(contentlength.getBytes());
    String alive = "Connection: Keep-Alive\r\n";
    outStream.write(alive.getBytes());
    String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
    outStream.write(host.getBytes());
    //写完HTTP请求头后根据HTTP协议再写一个回车换行
    outStream.write("\r\n".getBytes());
    //把所有文本类型的实体数据发送出来
    outStream.write(textEntity.toString().getBytes());    
    //把所有文件类型的实体数据发送出来
    for(FormFile uploadFile : files){
     StringBuilder fileEntity = new StringBuilder();
     fileEntity.append("--");
     fileEntity.append(BOUNDARY);
     fileEntity.append("\r\n");
     fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
     fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
     outStream.write(fileEntity.toString().getBytes());
     if(uploadFile.getInStream()!=null){
      byte[] buffer = new byte[1024];
      int len = 0;
      while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
      outStream.write(buffer, 0, len);
      }
      uploadFile.getInStream().close();
     }else{
      outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
     }
     outStream.write("\r\n".getBytes());
    }
    //下面发送数据结束标志,表示数据已经结束
    outStream.write(endline.getBytes());
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
     return false;
    }
    outStream.flush();
    outStream.close();
    reader.close();
    socket.close();
    return true;
 }
 
 /**
 * 提交数据到服务器
 * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
 * @param params 请求参数 key为参数名,value为参数值
 * @param file 上传文件
 */
 public static boolean post(String path, Map params, FormFile file) throws Exception{
  return post(path, params, new FormFile[]{file});
 }
 /**
 * 提交数据到服务器
 * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
 * @param params 请求参数 key为参数名,value为参数值
 * @param encode 编码
 */
 public static byte[] postFromHttpClient(String path, Map params, String encode) throws Exception{
 List formparams = new ArrayList();//用于存放请求参数
 for(Map.Entry entry : params.entrySet()){
  formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
 }
 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);
 HttpPost httppost = new HttpPost(path);
 httppost.setEntity(entity);
 HttpClient httpclient = new DefaultHttpClient();//看作是浏览器
 HttpResponse respOnse= httpclient.execute(httppost);//发送post请求 
 return readStream(response.getEntity().getContent());
 }

 /**
 * 发送请求
 * @param path 请求路径
 * @param params 请求参数 key为参数名称 value为参数值
 * @param encode 请求参数的编码
 */
 public static byte[] post(String path, Map params, String encode) throws Exception{
 //String params = "method=save&name="+ URLEncoder.encode("老毕", "UTF-8")+ "&age=28&";//需要发送的参数
 StringBuilder parambuilder = new StringBuilder("");
 if(params!=null && !params.isEmpty()){
  for(Map.Entry entry : params.entrySet()){
  parambuilder.append(entry.getKey()).append("=")
   .append(URLEncoder.encode(entry.getValue(), encode)).append("&");
  }
  parambuilder.deleteCharAt(parambuilder.length()-1);
 }
 byte[] data = parambuilder.toString().getBytes();
 URL url = new URL(path);
 HttpURLConnection cOnn= (HttpURLConnection)url.openConnection();
 conn.setDoOutput(true);//允许对外发送请求参数
 conn.setUseCaches(false);//不进行缓存
 conn.setConnectTimeout(5 * 1000);
 conn.setRequestMethod("POST");
 //下面设置http请求头
 conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
 conn.setRequestProperty("Accept-Language", "zh-CN");
 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 conn.setRequestProperty("Content-Length", String.valueOf(data.length));
 conn.setRequestProperty("Connection", "Keep-Alive");
 
 //发送参数
 DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
 outStream.write(data);//把参数发送出去
 outStream.flush();
 outStream.close();
 if(conn.getResponseCode()==200){
  return readStream(conn.getInputStream());
 }
 return null;
 }
 
 /**
 * 读取流
 * @param inStream
 * @return 字节数组
 * @throws Exception
 */
 public static byte[] readStream(InputStream inStream) throws Exception{
 ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
 byte[] buffer = new byte[1024];
 int len = -1;
 while( (len=inStream.read(buffer)) != -1){
  outSteam.write(buffer, 0, len);
 }
 outSteam.close();
 inStream.close();
 return outSteam.toByteArray();
 }
}

FormFile.java

package cn.itcast.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 上传文件
 */
public class FormFile {
 /* 上传文件的数据 */
 private byte[] data;
 private InputStream inStream;
 private File file;
 /* 文件名称 */
 private String filname;
 /* 请求参数名称*/
 private String parameterName;
 /* 内容类型 */
 private String cOntentType= "application/octet-stream";
 
 public FormFile(String filname, byte[] data, String parameterName, String contentType) {
 this.data = data;
 this.filname = filname;
 this.parameterName = parameterName;
 if(contentType!=null) this.cOntentType= contentType;
 }
 
 public FormFile(String filname, File file, String parameterName, String contentType) {
 this.filname = filname;
 this.parameterName = parameterName;
 this.file = file;
 try {
  this.inStream = new FileInputStream(file);
 } catch (FileNotFoundException e) {
  e.printStackTrace();
 }
 if(contentType!=null) this.cOntentType= contentType;
 }
 
 public File getFile() {
 return file;
 }

 public InputStream getInStream() {
 return inStream;
 }

 public byte[] getData() {
 return data;
 }

 public String getFilname() {
 return filname;
 }

 public void setFilname(String filname) {
 this.filname = filname;
 }

 public String getParameterName() {
 return parameterName;
 }

 public void setParameterName(String parameterName) {
 this.parameterName = parameterName;
 }

 public String getContentType() {
 return contentType;
 }

 public void setContentType(String contentType) {
 this.cOntentType= contentType;
 }
 
}

StreamTool.java

package cn.itcast.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {

 /**
 * 从输入流读取数据
 * @param inStream
 * @return
 * @throws Exception
 */
 public static byte[] readInputStream(InputStream inStream) throws Exception{
 ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
 byte[] buffer = new byte[1024];
 int len = 0;
 while( (len = inStream.read(buffer)) !=-1 ){
  outSteam.write(buffer, 0, len);
 }
 outSteam.close();
 inStream.close();
 return outSteam.toByteArray();
 }
}

MainActivity.java

package cn.itcast.uploaddata;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.itcast.net.HttpRequest;
import cn.itcast.utils.FormFile;
import cn.itcast.utils.SocketHttpRequester;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
 private static final String TAG = "MainActivity";
  private EditText timelengthText;
  private EditText titleText;
  private EditText videoText;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    Button button = (Button) this.findViewById(R.id.button);
    timelengthText = (EditText) this.findViewById(R.id.timelength);
    videoText = (EditText) this.findViewById(R.id.video);
    titleText = (EditText) this.findViewById(R.id.title);
    button.setOnClickListener(new View.OnClickListener() {  
  @Override
  public void onClick(View v) {
  String title = titleText.getText().toString();
  String timelength = timelengthText.getText().toString();
  Map params = new HashMap();
  params.put("method", "save");
  params.put("title", title);
  params.put("timelength", timelength);
  try {
  // HttpRequest.sendGetRequest("http://192.168.1.100:8080/videoweb/video/manage.do", params, "UTF-8");
   File uploadFile = new File(Environment.getExternalStorageDirectory(), videoText.getText().toString());
   FormFile formfile = new FormFile("02.mp3", uploadFile, "video", "audio/mpeg");
   SocketHttpRequester.post("http://192.168.1.100:8080/videoweb/video/manage.do", params, formfile);
   Toast.makeText(MainActivity.this, R.string.success, 1).show();
  } catch (Exception e) {
   Toast.makeText(MainActivity.this, R.string.error, 1).show();
   Log.e(TAG, e.toString());
  }
  }
 });
    
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • 本文介绍了在Mac上安装Xamarin并使用Windows上的VS开发iOS app的方法,包括所需的安装环境和软件,以及使用Xamarin.iOS进行开发的步骤。通过这种方法,即使没有Mac或者安装苹果系统,程序员们也能轻松开发iOS app。 ... [详细]
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • 本文介绍了在Windows环境下如何配置php+apache环境,包括下载php7和apache2.4、安装vc2015运行时环境、启动php7和apache2.4等步骤。希望对需要搭建php7环境的读者有一定的参考价值。摘要长度为169字。 ... [详细]
  • 本文介绍了在Linux下安装和配置Kafka的方法,包括安装JDK、下载和解压Kafka、配置Kafka的参数,以及配置Kafka的日志目录、服务器IP和日志存放路径等。同时还提供了单机配置部署的方法和zookeeper地址和端口的配置。通过实操成功的案例,帮助读者快速完成Kafka的安装和配置。 ... [详细]
  • mac php错误日志配置方法及错误级别修改
    本文介绍了在mac环境下配置php错误日志的方法,包括修改php.ini文件和httpd.conf文件的操作步骤。同时还介绍了如何修改错误级别,以及相应的错误级别参考链接。 ... [详细]
  • 如何提高PHP编程技能及推荐高级教程
    本文介绍了如何提高PHP编程技能的方法,推荐了一些高级教程。学习任何一种编程语言都需要长期的坚持和不懈的努力,本文提醒读者要有足够的耐心和时间投入。通过实践操作学习,可以更好地理解和掌握PHP语言的特异性,特别是单引号和双引号的用法。同时,本文也指出了只走马观花看整体而不深入学习的学习方式无法真正掌握这门语言,建议读者要从整体来考虑局部,培养大局观。最后,本文提醒读者完成一个像模像样的网站需要付出更多的努力和实践。 ... [详细]
author-avatar
kanney姜_958
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有