httpclient上传
❶ httpclient 怎么实现多文件上传 c/s java
虽然在JDK的java.net包中已经提供了访问HTTP协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。以下是简单的post例子:Stringurl="bbslogin2.php";PostMethodpostMethod=newPostMethod(url);//填入各个表单域的值NameValuePair[]data={newNameValuePair("id","youUserName"),newNameValuePair("passwd","yourPwd")};//将表单的值放入postMethod中postMethod.setRequestBody(data);//执行postMethodintstatusCode=httpClient.executeMethod(postMethod);//HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发//301或者302if(statusCode==HttpStatus.SC_MOVED_PERMANENTLY||statusCode==HttpStatus.SC_MOVED_TEMPORARILY){//从头中取出转向的地址HeaderlocationHeader=postMethod.getResponseHeader("location");Stringlocation=null;if(locationHeader!=null){location=locationHeader.getValue();System.out.println("Thepagewasredirectedto:"+location);}else{System.err.println("Locationfieldvalueisnull.");}return;}详情见:/developerworks/cn/opensource/os-httpclient/
❷ httpclient如何一起上传内容和图片
以文件的形式传参
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param actionUrl 访问的服务器URL
* @param params 普通参数
* @param files 文件参数
* @return
* @throws IOException
*/
public static void post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException
{
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet())
{
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null)
{
for (Map.Entry<String, File> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
// name是post中传参的键 filename是文件的名称
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
}
// return in.toString();
}
以数据流的形式传参
public static String postFile(String actionUrl, Map<String, String> params, Map<String, byte[]> files)
throws Exception
{
StringBuilder sb2 = null;
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(6 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet())
{
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null)
{
for (Map.Entry<String, byte[]> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
// InputStream is = new FileInputStream(file.getValue());
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = is.read(buffer)) != -1)
// {
// outStream.write(buffer, 0, len);
// }
// is.close();
outStream.write(file.getValue());
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
System.out.println(sb2.toString());
}
outStream.close();
conn.disconnect();
// 解析服务器返回来的数据
return ParseJson.getEditMadIconResult(sb2.toString());
}
else
{
return "Update icon Fail";
}
// return in.toString();
}
❸ 如何接收httpclient 文件上传
一般的情况下我们都是使用Chrome或者其他浏览器来访问一个WEB服务器,用来浏览页面查看信息或者提交一些数据、文件上传下载等等。所访问的这些页面有的仅仅是一些普通的页面,有的需要用户登录后方可使用,或者需要认证以及是一些通过加密方式传输,例如H
❹ HTTPclient使用MultipartEntity怎么上传文件
你先搞清楚 HTTPclient 是做什么用的
HTTPclient 的作用是在 jsp 中模拟一个浏览器,即 HTTP 协议的客户端(client)
你的后台代码是将你本地服务器上的文件像浏览器那样上传到目标服务器
于是 new File("C:\\1.txt") 的问题就可以解决了吧?C:\\1.txt 是你本地服务器中的文件,当然文件名是你自己定的
至于 multipart/form-data 声明,那是由 HttpPost 的参数 MultipartEntity 自动加上的
❺ android的自带的httpClient 怎么上传文件
分享一段前辈的demo,希望对你有帮助,
/**
* 上传文件
* @throws ParseException
* @throws IOException
*/
public static void postFile() throws ParseException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 要上传的文件的路径
String filePath = new String("F:/pic/001.jpg");
// 把一个普通参数和文件上传给下模李面这个地址 是一个servlet
HttpPost httpPost = new HttpPost(
"http://localhost:8080/xxx/xxx.action");
// 把文件转换成流对象FileBody
File file = new File(filePath);
FileBody bin = new FileBody(file);
StringBody uploadFileName = new StringBody(
"把我修改成文件名称", ContentType.create(
"正并text/plain", Consts.UTF_8));
//以浏览器兼容模式运行,防止文件名乱码。
HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("uploadFile", bin) //uploadFile对应服务端类的同名属性<File类型>
.addPart("uploadFileName", uploadFileName)//uploadFileName对应服务端类的同名属性<String类型>
.setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(reqEntity);
System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println("----------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
// 获取响应对举码迹象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印响应长度
System.out.println("Response content length: "
+ resEntity.getContentLength());
// 打印响应内容
System.out.println(EntityUtils.toString(resEntity,
Charset.forName("UTF-8")));
}
// 销毁
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
/**
* 下载文件
* @param url http://www.xxx.com/img/333.jpg
* @param destFileName xxx.jpg/xxx.png/xxx.txt
* @throws ClientProtocolException
* @throws IOException
*/
public static void getFile(String url, String destFileName)
throws ClientProtocolException, IOException {
// 生成一个httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
File file = new File(destFileName);
try {
FileOutputStream fout = new FileOutputStream(file);
int l = -1;
byte[] tmp = new byte[1024];
while ((l = in.read(tmp)) != -1) {
fout.write(tmp, 0, l);
// 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试
}
fout.flush();
fout.close();
} finally {
// 关闭低层流。
in.close();
}
httpclient.close();
}
❻ HTTPclient使用MultipartEntity怎么上传文件
上传文档方法:
进入网络文库后,点“上传我的文档”,会出现一个对话框,选择你想要上传的文档,再点击“开始上传”。
注意文档有格式要求,上传后等待审核,通过后即可与网友共享了。
上传附件方法:
步骤一:展开回答框,找到“上传”按钮
步骤二:点击“上传”按钮,从电脑中选择要上传的文件(目前只支持上传1个文件哦~如果有多个文件,可以进行打包上传~~)
步骤三:选中文件打开,显示文件上传进度。
步骤四:文件上传成功,进度条显示100%,可以对文件进行重命名操作~~
步骤五:回答编辑成功后,进入问题页显示,可供网友下载~~
❼ android的自带的httpClient 怎么上传文件
Android上传文件到服务端可以使用HttpConnection 上传文件,也可以使用Android封装好的HttpClient类。当仅仅上传文件可以直接使用httpconnection 上传比较方便快捷。
1、使用HttpConection上传文件。将文件转换成表单数据流。主要的思路就自己构造个http协议内容,服务端解析报文获得表单数据。代码片段:
[java] view plain
HttpURLConnection con;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(C_TimeOut);
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
/* 设置DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
FileInputStream fStream = new FileInputStream(file);
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while((length = fStream.read(buffer)) != -1)
{
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
fStream.close();
ds.flush();
ds.close();
可以参考
①《在 Android 上通过模拟 HTTP multipart/form-data 请求协议信息实现图片上传》 (http://bertlee.iteye.com/blog/1134576)。
②《关于android Http访问,上传,用了三个方法 》
2、使用Android HttpClient类上传参数。下面我在网上搜到得代码,忘记出处了
[java] view plain
private static boolean sendPOSTRequestHttpClient(String path,
Map<String, String> params) throws Exception {
// 封装请求参数
List<NameValuePair> pair = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 把请求参数变成请求体部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost对象设置发送的URL路径
HttpPost post = new HttpPost(path);
// 发送请求体
post.setEntity(uee);
// 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
Log.i("http", "httpclient");
return true;
}
return false;
}
3、使用httpClient上传文字信息和文件信息。使用httpClient上传文件非常的方便。不过需要导入apache-mime4j-0.6.jar 和httpmime-4.0.jar两个.jar包。
[java] view plain
// 封装请求参数
MultipartEntity mpEntity = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
StringBody par = new StringBody(entry.getValue());
mpEntity.addPart(entry.getKey(), par);
}
}
// 图片
if (!imagepath.equals("")) {
FileBody file = new FileBody(new File(imagepath));
mpEntity.addPart("photo", file);
}
// 使用HttpPost对象设置发送的URL路径
HttpPost post = new HttpPost(path);
// 发送请求体
post.setEntity(mpEntity);
// 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
FileBody类可以把文件封装到表单中,实现附件的上传。
关于httpClient上传文件可以参考链接: http://www.eoeandroid.com/forum.php?mod=viewthread&tid=76721&page=1
需要用的的ja下载地址r:http://download.csdn.net/detail/china1988s/3791514
参考:
①《在 Android 上通过模拟 HTTP multipart/form-data 请求协议信息实现图片上传》 (http://bertlee.iteye.com/blog/1134576)。
②《关于android Http访问,上传,用了三个方法 》
❽ android的自带的httpClient 怎么上传文件
在Android开发中,Android SDK附带了Apache的HttpClient,它是一个完善的客户端。它提供了对HTTP协议的全面支持,可以使用HttpClient的对象来执行HTTP GET和HTTP POST调用。
HTTP工作原理:
1.客户端(一般是指浏览器,这里是指自己写的程序)与服务器建立连接
2.建立连接后,客户端向服务器发送请求
3.服务器接收到请求后,向客户端发送响应信息
4.客户端与服务器断开连接
HttpClient的一般使用步骤:
1.使用DefaultHttpClient类实例化HttpClient对象
2.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
3.调用execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
4.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。
最后记得要在AndroidManifest.xml文件添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
附件中包含了一个拍照上传的源代码