import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

import android.content.Context;
import android.util.Log;

public class HttpPost {
	
    public static Boolean postSDFile(String urlstr, String msg, String filePath
            ) {

   final String TAG = "uploadFile";
   final int TIME_OUT = 10 * 1000; // 超时时间
   final String CHARSET = "utf-8"; // 设置编码
   
//String result = null;
String BOUNDARY = Base64.encode(msg);// UUID.randomUUID().toString(); //边界标识
// 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
int res = 0;

	
URL url;
InputStream is=null;

try {
	url = new URL(urlstr);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection(); 
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Content-Type", CONTENT_TYPE
+ ";boundary=" + BOUNDARY);



File f = new File(filePath);


if(!f.exists()){


	String write_str ="此文件已被删除";	
	 try{   		  
	       FileOutputStream fout = new FileOutputStream(f);   
	       byte [] bytes = write_str.getBytes();   
	  
	       fout.write(bytes);   
	       fout.close();   
	     }  
	  
	      catch(Exception e){   
	        e.printStackTrace();   
	       } 	
}

is = new FileInputStream(f);	





//is = context.openFileInput(filePath);// 打开文件流
if (is != null) {
	
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(
 conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/

sb.append("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
 + Base64.encode(filePath) + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
 + CHARSET + LINE_END);
sb.append(LINE_END);



dos.write(sb.toString().getBytes());

byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
System.out.println("aaaa"+len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
 .getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);

}


//result = sb1.toString();
//Log.e(TAG, "result : " + result);
}
} catch (MalformedURLException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (IOException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
}
 
if(res == 200){
return true;}
else{return false;}
}
	
	public static String PostMsg(String pathUrl, String msg) {


		StringBuffer sb = null;
		sb = new StringBuffer();
		try {
			
			// 建立连接
			URL url = new URL(pathUrl);
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

			//设置连接属性
			httpConn.setDoOutput(true);// 使用 URL 连接进行输出
			httpConn.setDoInput(true);// 使用 URL 连接进行输入
			httpConn.setUseCaches(false);// 忽略缓存
			httpConn.setRequestMethod("POST");// 设置URL请求方法
			String requestString = Base64.encode(msg);

			// 设置请求属性
			// 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
			byte[] requestStringBytes = requestString.getBytes();
			httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
			httpConn.setRequestProperty("Content-Type", "application/octet-stream");
			httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			httpConn.setRequestProperty("Charset", "UTF-8");

			// 建立输出流,并写入数据
			OutputStream outputStream = httpConn.getOutputStream();
			outputStream.write(requestStringBytes);
			outputStream.close();
			//System.out.println("1");
			// 获得响应状态
			int responseCode = httpConn.getResponseCode();
			
			if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功

				// 当正确响应时处理数据
				 
				String readLine;
				BufferedReader responseReader;
				// 处理响应流,必须与服务器响应流输出的编码一致
				responseReader = new BufferedReader(new InputStreamReader(
						httpConn.getInputStream()));
				while ((readLine = responseReader.readLine()) != null) {
					sb.append(readLine).append("\n");
				}
				responseReader.close();
                
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}	
		return sb.toString();
	}
}

posted on 2015-10-12 16:45  超宇  阅读(195)  评论(0编辑  收藏  举报