import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MyHttpClient {
private URL url;
private String host="";
private String referer="";
private HttpURLConnection con;
private OutputStream os;
private String delimiter = "--";
private String boundary = "APP"+Long.toString(System.currentTimeMillis())+"ANDROID";
public MyHttpClient(String url) throws MalformedURLException {
this.url=new URL(url);
host=this.url.getHost();
referer=url;
}
public void connect4Multipart() throws Exception {
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
con.setRequestProperty("Charset", "iso-8859-1");
con.setRequestProperty("connection", "keep-alive");
con.setRequestProperty("Referer", referer);
con.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 Greatwqs");
con.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");
con.setRequestProperty("Host", host);
con.setRequestProperty("Accept-Charset",
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
con.connect();
os = con.getOutputStream();
}
public void addFormPart(String paramName, String value) throws Exception {
writeParamData(paramName, value);
}
public void addFilePart(String paramName, String fileName, String path) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n" ).getBytes());
os.write( ("Content-Type: application/octet-stream\r\n" ).getBytes());
os.write( ("Content-Transfer-Encoding: binary\r\n" ).getBytes());
os.write("\r\n".getBytes());
File f = new File(path);
FileInputStream fis=new FileInputStream(f);
byte[] buf=new byte[1024];
while(true){
int len=fis.read(buf);
if(len>0){
os.write(buf, 0, len);
}else{
break;
}
}
fis.close();
os.write("\r\n".getBytes());
}
public void finishMultipart() throws Exception {
os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
os.flush();
os.close();
}
public String getResponse() throws Exception {
InputStream is = con.getInputStream();
byte[] b1 = new byte[1024];
StringBuilder buffer = new StringBuilder();
while ( is.read(b1) != -1){
buffer.append(new String(b1));
}
con.disconnect();
String rst=buffer.toString();
return rst;
}
private void writeParamData(String paramName, String value) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( "Content-Type: text/plain\r\n".getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"\r\n").getBytes());;
os.write( ("\r\n" + value + "\r\n").getBytes());
}
}