使用java代码提交图片到服务器
2014-07-23 17:41
363 查看
import java.io.IOException; import java.net.*; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.*; import javax.imageio.stream.*; /** * * @author zcwangjb */ public class HttpPostUtil { URL url; HttpURLConnection conn; String boundary = "--------httppost123"; Map<String, String> textParams = new HashMap<String, String>(); Map<String, File> fileparams = new HashMap<String, File>(); DataOutputStream ds; public HttpPostUtil() { } public HttpPostUtil(String url) throws Exception { this.url = new URL(url); } //重新设置要请求的服务器地址,即上传文件的地址。 public void setUrl(String url) throws Exception { this.url = new URL(url); } //增加一个普通字符串数据到form表单数据中 public void addTextParameter(String name, String value) { textParams.put(name, value); } //增加一个文件到form表单数据中 public void addFileParameter(String name, File value) { fileparams.put(name, value); } // 清空所有已添加的form表单数据 public void clearAllParameters() { textParams.clear(); fileparams.clear(); } // 发送数据到服务器,返回一个字节包含服务器的返回结果的数组 public byte[] send() throws Exception { initConnection(); try { conn.connect(); } catch (SocketTimeoutException e) { // something throw new RuntimeException(); } ds = new DataOutputStream(conn.getOutputStream()); writeFileParams(); writeStringParams(); paramsEnd(); InputStream in = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = in.read()) != -1) { out.write(b); } conn.disconnect(); return out.toByteArray(); } //文件上传的connection的一些必须设置 private void initConnection() throws Exception { conn = (HttpURLConnection) this.url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(10000); //连接超时为10秒 conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); } //普通字符串数据 private void writeStringParams() throws Exception { Set<String> keySet = textParams.keySet(); for (Iterator<String> it = keySet.iterator(); it.hasNext();) { String name = it.next(); String value = textParams.get(name); ds.writeBytes("--" + boundary + "\r\n"); ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n"); ds.writeBytes("\r\n"); ds.writeBytes(encode(value) + "\r\n"); } } //文件数据 private void writeFileParams() throws Exception { Set<String> keySet = fileparams.keySet(); for (Iterator<String> it = keySet.iterator(); it.hasNext();) { String name = it.next(); File value = fileparams.get(name); ds.writeBytes("--" + boundary + "\r\n"); ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + encode(value.getName()) + "\"\r\n"); ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n"); ds.writeBytes("\r\n"); ds.write(getBytes(value)); ds.writeBytes("\r\n"); } } //获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream private String getContentType(File f) throws Exception { // return "application/octet-stream"; // 此行不再细分是否为图片,全部作为application/octet-stream 类型 ImageInputStream imagein = ImageIO.createImageInputStream(f); if (imagein == null) { return "application/octet-stream"; } Iterator<ImageReader> it = ImageIO.getImageReaders(imagein); if (!it.hasNext()) { imagein.close(); return "application/octet-stream"; } imagein.close(); return "image/" + it.next().getFormatName().toLowerCase();//将FormatName返回的值转换成小写,默认为大写 } //把文件转换成字节数组 private byte[] getBytes(File f) throws Exception { FileInputStream in = new FileInputStream(f); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } in.close(); return out.toByteArray(); } //添加结尾数据 private void paramsEnd() throws Exception { ds.writeBytes("--" + boundary + "--" + "\r\n"); ds.writeBytes("\r\n"); } // 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码 private String encode(String value) throws Exception { return URLEncoder.encode(value, "UTF-8"); } public String detectImg(String url) { try { HttpPostUtil u = new HttpPostUtil(""); u.addFileParameter("image", new File(url)); // u.addTextParameter("text", "中文"); byte[] b = u.send(); String result = new String(b); System.out.println(result); return result; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static void main(String[] args) throws Exception { HttpPostUtil u = new HttpPostUtil(""); u.addFileParameter("image", new File("")); byte[] b = u.send(); String result = new String(b); System.out.println(result); } public void sendImgbyPost(String url, String postcontent) throws IOException { try { HttpURLConnection huc = (HttpURLConnection) new URL(url).openConnection(); huc.setDoInput(true); huc.setDoOutput(true); huc.setRequestMethod("POST"); PrintWriter pw = new PrintWriter(new OutputStreamWriter(huc.getOutputStream())); pw.print(postcontent); pw.close(); BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String content = ""; String line = br.readLine(); while (line != null) { content = content + line; line = br.readLine(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
相关文章推荐
- Java乔晓松-android使用GridView布局的电子相册&服务器获取图片
- Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端
- 使用Java代码获取服务器性能信息及局域网内主机名
- Android开发之下载服务器上的一张图片到本地java代码实现HttpURLConnection
- 在Java代码中使用pdfBox将PDF转换为图片
- Java乔晓松-android使用ImageSwitcher布局的电子相册&服务器获取图片
- 学习Java Web开发【2】可传输图片的服务器的代码编写
- 使用Java生成jpg与压缩图片为jpg文件的代码示例
- java使用jgit提交代码
- 使用XML布局文件和java代码共同控制UI界面做一个简易图片浏览器
- 意外作出了一个javascript的服务器,可以通过js调用并执行任何java(包括 所有java 内核基本库)及C#类库,并最终由 C# 执行你提交的javascript代码! 不敢藏私,特与大家分
- 解决Java代码中使用的图片应该放到哪个目录里的问题
- Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端
- 使用git提交代码到远程服务器
- SVN 服务器代码提交和更新 如何使用?
- 意外作出了一个javascript的服务器,可以通过js调用并执行任何java(包括 所有java 内核基本库)及C#类库,并最终由 C# 执行你提交的javascript代码! 不敢藏私,特与大家分
- Git使用教程(一)——Git提交代码到远程服务器
- 使用Netbeans远程调试服务器java代码
- [置顶] Android开发之下载服务器上的一张图片到本地java代码实现HttpURLConnection
- java POI导出excel(带有图片的数据)以及ftp上传图片到另一台服务器的方法参考代码