1、作为client发送和获取图片
1.1、发送图片 作为client时发送图片通常是通过from-data的multipart形式来发送的,这时我们就在模拟浏览器的form文件表单来提交请求,multipart形式的form表单内容一般如下清单:
对于这样的一个表单,当用户在点击submit时浏览器就会自动的组装一个multipart形式的POST请求,具体的请求体内容可以参见这篇文章http://www.voidcn.com/article/p-umvewndx-qu.html
那么在java里面我们怎么模拟multipart的from表单呢?
最原始的方法就是按照其协议形式我们自己来拼接一个请求的body来,并设置好相应的header头信息(当然就是有点费劲);另外一种方法就是调用java库中即有的Lib库文件(当然也是我们最推荐的)。
这里我们介绍的就是使用java的MultipartEntityBuilder类来实现向服务器端发送一个图片或者文件,具体的代码见如下清单:
String url = "http://your.server.com/postimage/service"
HttpPost httpPost = new HttpPost(url)
HttpParams httpParameters = new BasicHttpParams();
httpParameters.setParameter("charset", HTTP.UTF_8);
HttpConnectionParams.setConnectionTimeout(httpParameters, Integer.parseInt(CONNECTTIMEOUT));
HttpConnectionParams.setSoTimeout(httpParameters, Integer.parseInt(ReadTIMEOUT));
HttpClient httpClient = new DefaultHttpClient(httpParameters);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setCharset(Charset.forName(HTTP.UTF_8));
builder.addTextBody("uid", appKey, ContentType.create("text/plain", Charset.forName(HTTP.UTF_8)));
File image_file = new File("/path/image/file");
FileInputStream fis = new FileInputStream(image_file);
byte[] buf = new byte[(int) file.length()];
fis.read(buf);
fis.close();
builder.addBinaryBody("image_file", buf, ContentType.create(image_file.getContentType()), "image1.jpg");
HttpEntity httpEntity = builder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
InputStream inStream = httpResponse.getEntity().getContent();
ByteArrayOutputStream body = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = -1;
while ((len = inStream.read(buf)) != -1) {
body.write(buf, 0, len);
}
String res = new String(body.toByteArray(), HTTP.UTF_8);
1.2、获取图片 java从服务器端获取图片主要是通过请求图片对应的HTTP的url,然后下载图片到本地,保存到指定位置。具体的代码见清单
String url = "http://path.to.image/file"
String fullName = "/path/to/save/image";
File targetFile = new File(fullName);
int connectionTimeout = 10000;
int readTimeout = 15000;
FileUtils.copyURLToFile(new URL(url), targetFile, connectionTimeout, readTimeout); 2、作为server发送和接收图片