JavaHttp请求工具类实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
public class HttpPostUtils {
public static String doPost(String requestURL, String params, String proxyHost, Integer proxyPort) {
StringBuffer buffer = new StringBuffer();
HttpURLConnection conn = null;
try {
URL url = new URL(requestURL);
if (proxyHost != null && proxyPort != null) {
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) url.openConnection(proxy);
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setReadTimeout(60000);
conn.setConnectTimeout(60000);
conn.setDoInput(true);
if (params != null) {
conn.setRequestProperty("Content-type", "application/json");
OutputStream os = conn.getOutputStream();
try {
os.write(params.getBytes("UTF-8"));
} catch (Exception e) {
System.out.println("HttpPostUtils doPost error: " + e);
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
System.out.println("HttpPostUtils doPost error: " + e);
}
}
}
InputStream is = null;
InputStreamReader inputReader = null;
BufferedReader reader = null;
try {
is = conn.getInputStream();
inputReader = new InputStreamReader(is, "UTF-8");
reader = new BufferedReader(inputReader);
String temp;
while ((temp = reader.readLine()) != null) {
buffer.append(temp);
}
} catch (Exception e) {
System.out.println("HttpPostUtils doPost error: " + e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (inputReader != null) {
inputReader.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
System.out.println("HttpPostUtils doPost error: " + e);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return buffer.length()==0 ? "" : buffer.toString();
}
}