今天学到了HttpClient的使用,里面最关键的就是将表单和文件已Post方式提交到Java EE的项目中。
再做项目HttpClientDemo前,先写工具类,为以后的项目开发提供方便。
今天学到了HttpClient的使用,里面最关键的就是将表单和文件已Post方式提交到Java EE的项目中。
package com.example.httpclientdemo.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
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;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
public class NetUtil {
/**
* 该方法可以根据一个url返回一个图片
*
* @param address
* 得到图片的统一资源定位器地址
* @param flag
* 是否写入缓存
* @return 图片
* @throws Exception
*/
public static Bitmap getImg(String address, boolean flag) throws Exception {
// 声明 URL
URL url = new URL(address);
// 得到打开的链接
URLConnection conn = url.openConnection();
conn.setRequestProperty("method", "get");
conn.setReadTimeout(5000);
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
byte[] imgBytes = bos.toByteArray();
OutputStream fos = null;
if (flag) {
// 1.根据请求地址得到图片文件名
int start = address.lastIndexOf("/");
String iconName = address.substring(start + 1);
File iconfile = new File(Environment.getExternalStorageDirectory(),
iconName);
fos = new FileOutputStream(iconfile);
fos.write(imgBytes);
fos.flush();
fos.close();
}
return BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);
}
public static String getHtml(String address) throws Exception {
// 声明 URL
URL url = new URL(address);
// 得到打开的链接
URLConnection conn = url.openConnection();
conn.setRequestProperty("method", "get");
conn.setReadTimeout(5000);
InputStream is = conn.getInputStream();
// 得到网页编码类型
String contentType = conn.getContentType();
// 截取等号 = 得到结果如:utf-8、GBK
String type = contentType.split("=")[1];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
byte[] imgBytes = bos.toByteArray();
return new String(imgBytes, type);
}
public static String getJson(String address) throws Exception {
// 声明 URL
URL url = new URL(address);
// 得到打开的链接
URLConnection conn = url.openConnection();
conn.setRequestProperty("method", "get");
conn.setReadTimeout(5000);
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
byte[] imgBytes = bos.toByteArray();
return new String(imgBytes);
}
public static HttpResponse clientPost(String path,
NameValuePair... nameValuePairs) throws Exception {
// 得到模拟http客户端
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
List<NameValuePair> parameters = Arrays.asList(nameValuePairs);
HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
return response;
}
public static String clientPostFile(String path, String filepath)
throws Exception {
// 得到模拟http客户端
File file = new File(filepath);
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
Part[] parts = { new StringPart("name", "小王子"),
new StringPart("password", "xiaowangzi"),
new FilePart("file", file) };
PostMethod postMethod = new PostMethod(path);
postMethod.setRequestEntity(new MultipartRequestEntity(parts,
postMethod.getParams()));
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
int status = httpClient.executeMethod(postMethod);
if (status == 200) {
return new String(postMethod.getResponseBody());
} else {
throw new IllegalArgumentException("文件不存在,或者文件不存在。。。");
}
}
public static String getStringbyInputStream(InputStream is, String charset)
throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = is.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
return new String(bos.toByteArray(), charset);
}
public static String getStringbyInputStream(InputStream is)
throws IOException {
return getStringbyInputStream(is, "utf-8");
}
}
本文介绍了如何使用HttpClient进行文件的上传和下载操作,并提供了具体的代码实现。包括如何发送POST请求携带表单数据和文件,以及如何从指定URL获取图片和HTML内容。
1万+

被折叠的 条评论
为什么被折叠?



