import java.net.HttpURLConnection; try { URL url = new URL(路徑); //注意是HttpURLConnection,而不是HttpsURLConnection HttpURLConnection connection= (HttpURLConnection) url.openConnection(); //設(shè)置連接輸出流為true,默認(rèn)false (post 請(qǐng)求是以流的方式隱式的傳遞參數(shù)) connection.setDoOutput(true); //設(shè)置連接輸入流為true connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); //設(shè)置該HttpURLConnection實(shí)例是否自動(dòng)執(zhí)行重定向 connection.setInstanceFollowRedirects(true); //application/x-javascript text/xml->xml數(shù)據(jù) application/x-javascript->json對(duì)象 application/x-www-form-urlencoded->表單數(shù)據(jù) connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //建立連接 (請(qǐng)求未開(kāi)始,直到connection.getInputStream()方法調(diào)用時(shí)才發(fā)起,以上各個(gè)參數(shù)設(shè)置需在此方法之前進(jìn)行) connection.connect(); //創(chuàng)建輸入輸出流,用于往連接里面輸出攜帶的參數(shù),(輸出內(nèi)容為?后面的內(nèi)容) DataOutputStream dataout = new DataOutputStream(connection.getOutputStream()); String parm = "operate="+URLEncoder.encode("value", "UTF-8")+ "&operate2="+ URLEncoder.encode(value2, "UTF-8"); //將參數(shù)輸出到連接 dataout.writeBytes(parm); //輸出完成后刷新并關(guān)閉流 dataout.flush(); dataout.close(); // 重要且易忽略步驟 (關(guān)閉流,切記!) System.out.println(connection.getResponseCode()); //連接發(fā)起請(qǐng)求,處理服務(wù)器響應(yīng) (從連接獲取到輸入流并包裝為bufferedReader) BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line=""; StringBuilder sb = new StringBuilder(); // 用來(lái)存儲(chǔ)響應(yīng)數(shù)據(jù) while ((line = bf.readLine()) != null) { sb.append(line); } bf.close(); //重要且易忽略步驟 (關(guān)閉流,切記!) connection.disconnect(); //銷(xiāo)毀連接 } catch (IOException e) { responseErrorResult( response,"發(fā)送短信到短信系統(tǒng)錯(cuò)誤"+e); return "錯(cuò)誤:發(fā)送短信到短信系統(tǒng)錯(cuò)誤"+e; } return "正確:"+sb.toString(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// nanohttpd 類 @Override public Response serve(IHTTPSession session) { Map<String, String> params = session.getParms(); try { session.parseBody(params);//這步特別關(guān)鍵,如果不寫(xiě)這步的話,得到的post參 數(shù)全是null method = params.get("operate"); } catch (IOException | ResponseException e2) { e2.printStackTrace(); } } |
|
來(lái)自: yan的圖書(shū)41 > 《nanohttpd》