post请求上传文件
⑴ android中post请求怎么传输内容
一、需要用到的场景
在jQuery中使用$.post()就可以方便的发起一个post请求,在android程序中有时也要从服务器获取一些数据,就也必须得使用post请求了。
二、需要用到的主要类
在android中使用post请求主要要用到的类是HttpPost、HttpResponse、EntityUtils
三、主要思路
1、创建HttpPost实例,设置需要请求服务器的url。
2、为创建的HttpPost实例设置参数,参数设置时使用键值对的方式用到NameValuePair类。
3、发起post请求获取返回实例HttpResponse
4、使用EntityUtils对返回值的实体进行处理(可以取得返回的字符串,也可以取得返回的byte数组)
代码也比较简单,注释也加上了,就直接贴出来了
[java]
package com.justsy.url;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
public class HttpURLActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("start url...");
String url = "http://192.168.2.112:8080/JustsyApp/Applet";
// 第一步,创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
// 设置HTTP POST请求参数必须用NameValuePair对象
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("action", "downloadAndroidApp"));
params.add(new BasicNameValuePair("packageId", "89dcb664-50a7-4bf2-aeed-49c08af6a58a"));
params.add(new BasicNameValuePair("uuid", "test_ok1"));
HttpResponse httpResponse = null;
try {
// 设置httpPost请求参数
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(httpPost);
//System.out.println(httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 第三步,使用getEntity方法活得返回结果
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println("result:" + result);
T.displayToast(HttpURLActivity.this, "result:" + result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end url...");
setContentView(R.layout.main);
}
}
ADD:使用HttpURLConnection 进行post请求
[java]
String path = "http://192.168.2.115:8080/android-web-server/httpConnectServlet.do?PackageID=89dcb664-50a7-4bf2-aeed-49c08af6a58a";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
System.out.println(conn.getResponseCode());
============================================================================================================================
通过get和post方式向服务器发送请求
首先说一下get和post的区别
get请求方式是将提交的参数拼接在url地址后面,例如http://www..com/index.jsp?num=23&jjj=888;
但是这种形式对于那种比较隐私的参数是不适合的,而且参数的大小也是有限制的,一般是1K左右吧,对于上传文件
就不是很适合。
post请求方式是将参数放在消息体内将其发送到服务器,所以对大小没有限制,对于隐私的内容也比较合适。
如下Post请求
POST /LoginCheck HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://192.168.2.1/login.asp
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 192.168.2.1
Content-Length: 39
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: language=en
Username=admin&checkEn=0&Password=admin //参数位置
在android中用get方式向服务器提交请求:
在android模拟器中访问本机中的tomcat服务器时,注意:不能写localhost,因为模拟器是一个单独的手机系统,所以要写真是的IP地址。
否则无法访问到服务器。
//要访问的服务器地址,下面的代码是要向服务器提交用户名和密码,提交时中文先要经过URLEncoder编码,因为模拟器默认的编码格式是utf-8
//而tomcat内部默认的编码格式是ISO8859-1,所以先将参数进行编码,再向服务器提交。
private String address = "http://192.168.2.101:80/server/loginServlet";
public boolean get(String username, String password) throws Exception {
username = URLEncoder.encode(username);// 中文数据需要经过URL编码
password = URLEncoder.encode(password);
String params = "username=" + username + "&password=" + password;
//将参数拼接在URl地址后面
URL url = new URL(address + "?" + params);
//通过url地址打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时时间
conn.setConnectTimeout(3000);
//设置请求方式
conn.setRequestMethod("GET");
//如果返回的状态码是200,则一切Ok,连接成功。
return conn.getResponseCode() == 200;
}
在android中通过post方式提交数据。
public boolean post(String username, String password) throws Exception {
username = URLEncoder.encode(username);// 中文数据需要经过URL编码
password = URLEncoder.encode(password);
String params = "username=" + username + "&password=" + password;
byte[] data = params.getBytes();
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
//这是请求方式为POST
conn.setRequestMethod("POST");
//设置post请求必要的请求头
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 请求头, 必须设置
conn.setRequestProperty("Content-Length", data.length + "");// 注意是字节长度, 不是字符长度
conn.setDoOutput(true);// 准备写出
conn.getOutputStream().write(data);// 写出数据
return conn.getResponseCode() == 200;
}
⑵ 如何用POST方法上传文件
POST方法上传文件 随着php不断的完善,PHP对文件上传的支持也越来越完美,在PHP 4.0.3以前我们只能用() 和 is_uploaded_file()方法结合来上传文件,呵呵,其实就是这样我们也会感觉到PHP相对于ASP来说上传文件要方便很多,这也就是本人选择PHP的一点小小的引以为豪的地方。PHP 4.0.3之后PHP又出了一个新函数move_uploaded_file()。上传文件相对来说又简便了不少,只要这一个函数就行(我可不是说上传文件系统只要就一个函数就足够了,大家可不要误解我的意思,我的意思是move_uploaded_file是上传文件的一个核心函数)。 好了,我们看一个三个函数的讲解(资料来自:PHP手册)。 (string source,string desk); 将文件从 source 拷贝到 dest。如果成功则返回 TRUE,失败则返回 FALSE。 例: if (!($file, $file.'.bak')) { print ("failed to $file...<br>\n"); } is_uploaded_file(string filename) 如果 filename 所给出的文件是通过 HTTP POST 上传的则返回 TRUE。 move_uploaded_file(string filename, string destination) 本函数检查并确保由 filename 指定的文件是合法的上传文件(即通过 PHP 的 HTTP POST 上传机制所上传的)。如果文件合法,则将其移动为由 destination 指定的文件。 由三个函数的解释就可以得到一个结论,move_uploaded_file()是()和is_uploaded_file()函数的结合 讲了这么半天大家用起这三个函数可能还会有些生疏,下面给大家两个例子: 首先,建立一个前台页面,命名为index.html Code代码如下: <form enctype="multipart/form-data" action="_URL_" method="post"> Send this file: <input name="filename" type="file"> <input type="submit" value="Send File"> </form> 1,下面是关于()和is_uploaded_file()方法上传文件的方法(保存为:.php,上传文件需要将index.html中的_URL_改为.php) Code代码如下: <?php $path="./uploadfiles/"; if(is_uploaded_file($filename)) //特别注意这里,传递给is_uploaded_file的为$filename,可不要传递$_FILES["filename"]["name"] { $file1=$_FILES["filename"]["name"]; //注意这里$_FILES[]方法为PHP4.1.0及以上版本支持,PHP以下的版本要用$HTTP_POST_FILES[]方法 $file2=$path.time().$file1; $flag=1; } if($flag) $result=($_FILES['filename']['tmp_name'],$file2); if($result) echo "上传成功!"; ?> 2,下面是关于move_uploaded_file()方法上传文件的方法(保存为:move.php,上传文件需要将index.html中的_URL_改为move.php) Code代码如下: <?php $path="./uploadfiles/"; if($_FILES["filename"]["name"]){ $file1=$_FILES["filename"]["name"]; $file2 = $path.time().$file1; $flag=1; } if($flag) $result=move_uploaded_file($_FILES["filename"]["tmp_name"],$file2); //特别注意这里传递给move_uploaded_file的第一个参数为上传到服务器上的临时文件 if($result) echo "上传成功!"; ?> 文件上传就讲到这里了,这只是两个小程序,其实要完成文件上传所要的代码可不是这些就能了事的。一般还要有文件大小限制,文件扩展名选取,还有一些其它的安全方案。
⑶ 如何在 python 中模拟 post 表单来上传文件
在机器上安装了Python的setuptools工具,可以通过下面的命令来安装 poster:
easy_installposter
装完之后,安装下面代码就可以实现post表单上传文件了:
fromposter.encodeimportmultipart_encode
fromposter.streaminghttpimportregister_openers
importurllib2
#在urllib2上注册http流处理句柄
register_openers()
#开始对文件"DSC0001.jpg"的multiart/form-data编码
#"image1"是参数的名字,一般通过HTML中的<input>标签的name参数设置
#headers包含必须的Content-Type和Content-Length
#datagen是一个生成器对象,返回编码过后的参数
datagen,headers=multipart_encode({"image1":open("DSC0001.jpg","rb")})
#创建请求对象(localhost服务器IP地址,5000服务器端口)
request=urllib2.Request("http://localhost:5000/upload_image",datagen,headers)
#实际执行请求并取得返回
printurllib2.urlopen(request).read()
⑷ Okhttp 使用(同步、异步/get、post/上传文件)
目前Android端调用网络请求最常用的框架就是OKHttp,目前项目中也经常会用到。OKHTTP有哪些特点呢?下面是官网给出的OKHTTP的特点:
官网地址: https://square.github.io/okhttp/
想要详细了解HTTP/2,可以参考: https://www.jianshu.com/p/828a29bced9f
接下来就可以愉快的开始使用OKhttp进行开发了。
OKhttpclient通过builder构建,构建的时候涉及到很多配置项,本次简单对其中一些配置项做了说明,后续会对一些重要的配置项做专题说明正察。在实际的项目中的配置项根据项目具体需求进行配置。
上述配置项中比较常用的有
同步get请求会阻塞当前线程直到返回举枝茄结果,请求大致分为四个步骤:
异步请求方式的步骤和上述前两个步骤基本搭拍一致,主要发起请求的方式发生了变化,结果通过回调返回。这种请求方式对请求的线程没有限制。
与get请求方式不同的是post请求需要构建RequestBody,在请求时携带RequestBody。
⑸ Java利用HttpURLConnection发送post请求上传文件
在页面里实现上传文件不是什么难事 写个form 加上enctype = multipart/form data 在写个接收的就可以了 没租裤什么难的 如果要用 HttpURLConnection来实现文件上传 还真有点搞头 : )
先写个servlet把接收到的 HTTP 信息保存在一个文件中 看一下 form 表单到底封装了什么样的信息
Java代码
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
//获取输入流 是HTTP协议中的实体内容
ServletInputStream in=request getInputStream();
//缓冲区
byte buffer[]=new byte[ ];
FileOutputStream out=new FileOutputStream( d:\test log );
int len=sis read(buffer );
//把流里的信息循环读入到file log文件中
while( len!= ){
out write(buffer len);
len=in readLine(buffer );
}
out close();
in close();
}
来一个form表单
<form name= upform action= upload do method= POST
enctype= multipart/form data >
参数<input type= text name= username /><br/>
文件 <input type= file name= file /><br/>
文件 <input type= file name= file /><br/>
<input type= submit value= Submit />
<br />
</form>
假如我参数写的内容是hello word 然后二个文件是二个简单的txt文件梁誉 上传后test log里如下
Java代码
da e c
Content Disposition: form data; name= username
hello word
da e c
Content Disposition: form data; name= file ; filename= D:haha txt
Content Type: text/plain
haha
hahaha
da e c
Content Disposition: form data; name= file ; filename= D:huhu txt
Content Type: text/plain
messi
huhu
da e c
研究下规律发现有如下几点特征
第一行是 d b bc 作为分隔符 然后是 回车换行符 这个 d b bc 分隔符浏览器是随机生成的
第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=对应input的name值 filename对应要上传的文件名(包括路径在内)
第三行如果是文件就有Content Type: text/plain 这里上传的是txt文件所以是text/plain 如果上穿的是jpg图片的话就是image/jpg了 可以自己试试看看
然后就是回弊渣简车换行符
在下就是文件或参数的内容或值了 如 hello word
最后一行是 da e c 注意最后多了二个 ;
有了这些就可以使用HttpURLConnection来实现上传文件功能了
Java代码 public void upload(){
List<String> list = new ArrayList<String>(); //要上传的文件名 如 d:haha doc 你要实现自己的业务 我这里就是一个空list
try {
String BOUNDARY = d a d c ; // 定义数据分隔线
URL url = new URL( );
HttpURLConnection conn = (HttpURLConnection) url openConnection();
// 发送POST请求必须设置如下两行
conn setDoOutput(true);
conn setDoInput(true);
conn setUseCaches(false);
conn setRequestMethod( POST );
conn setRequestProperty( connection Keep Alive );
conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );
conn setRequestProperty( Charsert UTF );
conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);
OutputStream out = new DataOutputStream(conn getOutputStream());
byte[] end_data = ( + BOUNDARY + ) getBytes();// 定义最后数据分隔线
int leng = list size();
for(int i= ;i<leng;i++){
String fname = list get(i);
File file = new File(fname);
StringBuilder *** = new StringBuilder();
*** append( );
*** append(BOUNDARY);
*** append( );
*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );
*** append( Content Type:application/octet stream );
byte[] data = *** toString() getBytes();
out write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = ;
byte[] bufferOut = new byte[ ];
while ((bytes = in read(bufferOut)) != ) {
out write(bufferOut bytes);
}
out write( getBytes()); //多个文件时 二个文件之间加入这个
in close();
}
out write(end_data);
out flush();
out close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));
String line = null;
while ((line = reader readLine()) != null) {
System out println(line);
}
} catch (Exception e) {
System out println( 发送POST请求出现异常! + e);
e printStackTrace();
}
lishixin/Article/program/Java/hx/201311/27114