HttpClient 传输文件与其他值

因为工作上些问题,要用httpClient传些参数和一个文件到服务器,网上找了些例子然后结合一下我们这边用的webservice接口,最后就搞出个这么个东西来...

客户端:

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;

import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

public class test{
public static void main(String[] args) {

String url="http://127.0.0.1:8080/LearnServlet/FileUpdateServer";
String queryString = "a=123456&b=333333333333";
try {
FileInputStream in = new FileInputStream(new File("E://HeadFirstJava_CH_PDF.rar"));
PostHttpClient postHttpClient=new PostHttpClient();
postHttpClient.postHttpReq(queryString,url,in);
} catch (Exception e) {
e.printStackTrace();
}
}


public static String postHttpReq(String queryString,String url,InputStream in) {
HttpClient httpClient = new HttpClient();
EntityEnclosingMethod postMethod = new PostMethod(url);
postMethod.setQueryString(queryString);
postMethod.setRequestHeader("Content-Type", "application/octet-stream");

RequestEntity request = new InputStreamRequestEntity(in);
postMethod.setRequestEntity(request);


String responseMsg = "";
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(postMethod);// 发送请求
responseMsg = postMethod.getResponseBodyAsString();// 获取返回值
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();// 释放连接
}

return responseMsg;
}
}


服务端:

public class FileUpdateServer extends HttpServlet{
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException{
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String a = request.getParameter("a");
String b = request.getParameter("b");
System.out.println("11"+a+b); //11123456333333333333
InputStream in = request.getInputStream();
this.save(in, "testaa.torrent", "E://"); //这个就是个将流输出成文件的方法.....
}
}


嘛,大概就是这个样子...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值