用Java模拟表单(或iPhone、Android客户端)上传文件

来源:互联网 发布:中小学教育网网络课程 编辑:程序博客网 时间:2024/05/20 06:41

开发一个iPhone客户端,客户端调用我写的接口上传图片。工程需要自己测试,网上Google,找到了一个可用的代码。

参考:http://bigcat.easymorse.com/?p=764

package com.test;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.multipart.FilePart;import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;import org.apache.commons.httpclient.methods.multipart.Part;public class Main3 {/** * @param args * @throws IOException * @throws HttpException */public static void main(String[] args) throws HttpException, IOException {File file = new File("d:/abcd.jpg");PostMethod filePost = new PostMethod("http://localhost/feed/UploadFeedPicture.do");Part[] parts = { new FilePart("picture", file) };filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));HttpClient clients = new HttpClient();int status = clients.executeMethod(filePost);try {BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream(), "UTF-8"));StringBuffer stringBuffer = new StringBuffer();String line;while ((line = rd.readLine()) != null) {stringBuffer.append(line);}rd.close();System.out.println("接受到的流是:" + stringBuffer + "—-" + status);} catch (Exception e) {throw new RuntimeException("error", e);}}}


原创粉丝点击