java模擬提交form表單
阿新 • • 發佈:2019-01-31
public static void connectionUrl(String username,String password){
String url = "http://localhost:8080/aaa/bbb.action";
String responseMessage = "";
StringBuffer response = new StringBuffer();
HttpURLConnection httpConnection = null;
OutputStreamWriter out = null ;
BufferedReader reader = null;
try {
URL urlPost = new URL(url);
httpConnection = (HttpURLConnection) urlPost.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
// 引數長度太大,不能用get方式
httpConnection.setRequestMethod("POST" );
// 不使用快取
httpConnection.setUseCaches(false);
// URLConnection.setInstanceFollowRedirects是成員函式,僅作用於當前函式
httpConnection.setInstanceFollowRedirects(true);
// 配置本次連線的Content-type,配置為application/x-www-form-urlencoded的
// 意思是正文是urlencoded編碼過的form引數
httpConnection.setRequestProperty("Connection", "Keep-Alive");
// 設定請求頭資訊
httpConnection.setRequestProperty("Charset", "UTF-8");
// 設定邊界
String BOUNDARY = "----------" + System.currentTimeMillis();
httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 連線,從postUrl.openConnection()至此的配置必須要在connect之前完成,
// 要注意的是connection.getOutputStream會隱含的進行connect。
// 實際上只是建立了一個與伺服器的tcp連線,並沒有實際傳送http請求。
httpConnection.connect();
out = new OutputStreamWriter(httpConnection.getOutputStream(),"UTF-8");
// 正文,正文內容其實跟get的URL中'?'後的引數字串一致
/*JSONObject jsonObject=new JSONObject();
try{
jsonObject.put("username", username);
jsonObject.put("password", password);
jsonObject.put("captcha", captcha);
}catch(Exception e){
e.printStackTrace();
}*/
/*
Map parames = new HashMap<String, String>();
parames.put("username", "username");
parames.put("username", "username");
parames.put("captcha", "captcha");
*/
// 構建請求引數
StringBuffer sb = new StringBuffer();
sb.append("username="+username+"&password="+password);
//寫入引數,DataOutputStream.writeBytes將字串中的16位的unicode字元以8位的字元形式寫道流裡面
out.write(sb.toString());
System.out.println("send_url:" + url);
System.out.println("send_data:" + sb.toString());
// flush and close
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.close();
}
if (null != reader) {
reader.close();
}
if (null != httpConnection) {
httpConnection.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
try {
reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(),"UTF-8"));
while ((responseMessage = reader.readLine()) != null) {
response.append(responseMessage);
response.append("\n");
}
if (!"failure".equals(response.toString())) {
System.out.println("success");
} else {
System.out.println("failue");
}
// 將該url的配置資訊快取起來
System.out.println(response.toString());
System.out.println(httpConnection.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
connectionUrl("張三","123456");
}