- 代码 1
- import java.io.ByteArrayOutputStream;
- import java.io.DataOutputStream;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.Map;
- import android.util.Log;
- public class NetUtil {
- private static final String TAG = "NetUtil";
- private static final int RESPONSE_OK = 200;
- public static InputStream sendPostRequest(String urlPath,
- Map<String, String> params, String encoding) throws Exception {
- // String param = "method=save&id=24&name="
- // + URLEncoder.encode("大圆", "UTF-8");
- StringBuilder sb = new StringBuilder();
- for (Map.Entry<String, String> entry : params.entrySet()) {
- sb.append(entry.getKey()).append("=")
- .append(URLEncoder.encode(entry.getValue(), encoding))
- .append("&");
- }
- sb.deleteCharAt(sb.lastIndexOf("&"));
- byte[] data = sb.toString().getBytes();
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setReadTimeout(5 * 1000);
- conn.setDoOutput(true); // 发送POST请求, 必须设置容许输出
- conn.setUseCaches(false);
- conn.setRequestProperty("Connection", "Keep-Alive"); // 维持长连接
- conn.setRequestProperty("Charset", "UTF-8");
- // 设置输入参数的大小,把参数转化为字节数组
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- // 设置数据类型
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- DataOutputStream outStream = new DataOutputStream(
- conn.getOutputStream());
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if (conn.getResponseCode() == RESPONSE_OK) {
- return conn.getInputStream();
- }
- return null;
- }
- /*
- * 获得http返回的输入流,而且转化成String
- */
- public static String getTextContent(String urlPath, String encoding)
- throws Exception {
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setReadTimeout(5 * 1000);
- if (conn.getResponseCode() == RESPONSE_OK) {
- InputStream inStream = conn.getInputStream();
- byte[] data = readStream(inStream);
- System.out.println(new String(data, encoding));
- return new String(data, encoding);
- }
- return null;
- }
- // 读取数据
- public static byte[] readStream(InputStream inStream) throws Exception {
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[2048];
- int length = -1;
- while ((length = (inStream.read(buffer))) != -1) {
- outStream.write(buffer, 0, length);
- }
- outStream.close();
- return outStream.toByteArray();
- }
- // 直接返回http获得的输入流
- public static InputStream getStreamContent(String urlPath, String encoding)
- throws Exception {
- InputStream inStream = null;
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setReadTimeout(5 * 1000);
- if (conn.getResponseCode() == RESPONSE_OK) {
- inStream = conn.getInputStream();
- }
- return inStream;
- }
- public static void print(String tag, String msg) {
- Log.d(tag, msg);
- }
- }
- 代码 1 public class FormFile {
- // 上传文件的数据
- private byte[] data;
- private InputStream inStream;
- // 文件名称
- private String filename;
- // 表单名称
- private String formname;
- // 内容类型
- private String contentType = "application/octet-stream";
- public FormFile(String filename, byte[] data, String formname,
- String contentType) {
- this.data = data;
- this.filename = filename;
- this.formname = formname;
- if (contentType != null) {
- this.contentType = contentType;
- }
- }
- public FormFile(String filename, InputStream inStream, String formname,
- String contentType) {
- this.filename = filename;
- this.formname = formname;
- this.inStream = inStream;
- if (contentType != null) {
- this.contentType = contentType;
- }
- }
- public byte[] getData() {
- return data;
- }
- public void setData(byte[] data) {
- this.data = data;
- }
- public InputStream getInStream() {
- return inStream;
- }
- public void setInStream(InputStream inStream) {
- this.inStream = inStream;
- }
- public String getFilename() {
- return filename;
- }
- public void setFilename(String filename) {
- this.filename = filename;
- }
- public String getFormname() {
- return formname;
- }
- public void setFormname(String formname) {
- this.formname = formname;
- }
- public String getContentType() {
- return contentType;
- }
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
- }
- 代码 1 public class HttpUploadRequester {
- /**
- * 直接经过HTTP协议提交数据到服务器,实现以下面表单提交功能: <FORM METHOD=POST
- * ACTION="http://192.168.0.200:8080/ssi/fileload/test.do"
- * enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT
- * TYPE="text" NAME="id"> <input type="file" name="p_w_picpathfile"/> <input
- * type="file" name="zip"/> </FORM>
- *
- * @param actionUrl
- * 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,由于它会指向手机模拟器,
- * 你能够使用http://192.168.1.10:8080这样的路径测试)
- * @param params
- * 请求参数 key为参数名,value为参数值
- * @param file
- * 上传文件
- */
- // http协议中分割符,随便定义
- private static final String HTTP_BOUNDARY = "---------9dx5a2d578c2";
- private static final String MULTIPART_FORM_DATA = "multipart/form-data";
- private static final String LINE_ENTER = "\r\n"; // 换行 回车
- private static final int RESPONSE_OK = 200;
- public static String post(String urlPath, Map<String, String> params,
- FormFile[] formFiles) {
- try {
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setReadTimeout(5 * 1000);
- conn.setDoOutput(true); // 发送POST请求, 必须设置容许输出
- conn.setUseCaches(false);
- conn.setRequestProperty("Connection", "Keep-Alive"); // 维持长连接
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
- + "; boundary=" + HTTP_BOUNDARY);
- StringBuilder formItemData = new StringBuilder();
- // 构建 表单字段内容
- for (Map.Entry<String, String> entry : params.entrySet()) {
- formItemData.append("--");
- formItemData.append(HTTP_BOUNDARY);
- formItemData.append(LINE_ENTER);
- formItemData.append("Content-Disposition: form-data; name=\""
- + entry.getKey() + "\"\r\n\r\n");
- formItemData.append(entry.getValue());
- formItemData.append(LINE_ENTER);
- }
- DataOutputStream outStream = new DataOutputStream(
- conn.getOutputStream());
- // 发送表单字段内容到服务器
- outStream.write(formItemData.toString().getBytes());
- // 发送上传文件数据
- for (FormFile fileData : formFiles) {
- StringBuilder fileSplit = new StringBuilder();
- fileSplit.append("--");
- fileSplit.append(HTTP_BOUNDARY);
- fileSplit.append(LINE_ENTER);
- fileSplit.append("Content-Disposition: form-data;name=\""
- + fileData.getFormname() + "\";filename=\""
- + fileData.getFilename() + "\"\r\n");
- fileSplit.append("Content-Type:" + fileData.getContentType()
- + LINE_ENTER + LINE_ENTER);
- outStream.write(fileSplit.toString().getBytes());
- if (fileData.getInStream() != null) {
- byte[] buffer = new byte[1024];
- int length = 0;
- while ((length = fileData.getInStream().read()) != -1) {
- outStream.write(buffer, 0, length);
- }
- fileData.getInStream().close();
- } else {
- outStream.write(fileData.getData(), 0,
- fileData.getData().length);
- }
- outStream.write(LINE_ENTER.getBytes());
- }
- // 数据结束标志
- byte[] endData = ("--" + HTTP_BOUNDARY + "--" + LINE_ENTER)
- .getBytes();
- outStream.write(endData);
- outStream.flush();
- outStream.close();
- int responseCode = conn.getResponseCode();
- if (responseCode != RESPONSE_OK) {
- throw new RuntimeException("请求url失败");
- }
- InputStream is = conn.getInputStream();
- int ch;
- StringBuilder b = new StringBuilder();
- while ((ch = is.read()) != -1) {
- b.append((char) ch);
- }
- Log.i("HttpPost", b.toString());
- conn.disconnect();
- return b.toString();
- } catch (Exception e) {
- throw new RuntimeException();
- }
- }
- // 上传单个文件
- public static String post(String urlPath, Map<String, String> params,
- FormFile formFiles) {
- return post(urlPath, params, new FormFile[] { formFiles });
- }
- }
- 代码 1 // 以表单方式发送请求
- public static void sendDataToServerByForm() throws Exception {
- Map<String, String> params = new HashMap<String, String>();
- params.put("method", "sendDataByForm");
- params.put("strData", "字符串数据");
- // 获取SDCard中的good.jpg
- File file = new File(Environment.getExternalStorageDirectory(),
- "app_Goog_Android_w.png");
- FormFile fileData = new FormFile("app_Goog_Android_w.png", new FileInputStream(file),
- "fileData", "application/octet-stream");
- HttpUploadRequester.post(
- "http://192.168.0.2:8080/AndroidWebServer/server.do", params,
- fileData);
- }