import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpOrderUtil {
// 接口
private static final String post_url = "接口的地址";
public static String httpURLConnectionPOST(需要传的参数) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(post_url);//把字符串转换为URL请求地址
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();//此时cnnection只是为一个连接对象,待连接中
connection.setConnectTimeout(5 * 1000);//设置连接超时时间为5秒
connection.setReadTimeout(20 * 1000);//设置读取超时时间为20秒
connection.setDoOutput(true);//设置连接输出流为true,默认false
connection.setDoInput(true);//设置连接输入流为true
connection.setRequestMethod("POST");//设置请求方式为post
connection.setUseCaches(false);// post请求缓存设为false
connection.setInstanceFollowRedirects(true);//设置该HttpURLConnection实例是否自动执行重定向
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");//请求的content-type为application/x-www-form-urlencoded;
//charset=UTF-8
connection.connect();//建立连接
DataOutputStream dataout = new DataOutputStream(
connection.getOutputStream());//创建输入输出流,用于往连接里面输出携带的参数
String 参数= "参数="
+ URLEncoder.encode(需要传的参数, "utf-8");
dataout.writeBytes(参数);
dataout.flush();//输出完成后刷新并关闭流
dataout.close();
//System.out.println(connection.getResponseCode());
// 如果请求响应码是200,则表示成功
if (connection.getResponseCode() == 200) {
BufferedReader bf = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String line;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
bf.close();
}
connection.disconnect();//断开连接
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}