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();
}
}