import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.content.Context;
/**
* 向服务器端发送POST数据
* @author LinHang_He
*
*/
public class PostUtils {
private String path;
private Context context=null;
public PostUtils(String path)
{
this.path=path;
}
/**
* 构造函数
* @param path 请求URL地址
* @param context 当前上下文对象
*/
public PostUtils(String path,Context context)
{
this.path=path;
this.context=context;
}
/**
* 发送POST请求
* @param str 向服务器端发送的数据
* @return
*/
public String setPostRequest(String str){
try {
byte [] entity=str.getBytes();
HttpURLConnection conn=(HttpURLConnection)new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",String.valueOf(entity.length));
OutputStream outStream=conn.getOutputStream();
outStream.write(entity);
InputStream is=conn.getInputStream();
if(conn.getResponseCode()==200)
{
return inputStreamToString(is,"utf-8");
}
else{
System.out.println("error");
return "timeout";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "timeout";
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "timeout";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "timeout";
}
}
/**
* 将字符流转换成字符串
* @param is 输入数据流
* @param encoding 字符编码
* @return
*/
private String inputStreamToString(InputStream is, String encoding) {
try {
// byte[] b = new byte[1024];
byte[] b = new byte[1];
String res = "";
if (is == null) {
return "";
}
int bytesRead = 0;
while (true) {
bytesRead = is.read(b, 0, 1); // return final read bytes counts
if (bytesRead == -1) {// end of InputStream
return res;
}
res += new String(b, 0, bytesRead, encoding); // convert to string using bytes
}
} catch (Exception e) {
e.printStackTrace();
System.out.print("Exception: " + e);
return "";
}
}
}