postjava的簡單介紹

本文目錄一覽:

java HttpPost怎麼傳遞參數

public class HttpURLConnectionPost {

/**

* @param args

* @throws IOException

*/

public static void main(String[] args) throws IOException {

readContentFromPost();

}

public static void readContentFromPost() throws IOException {

// Post請求的url,與get不同的是不需要帶參數

URL postUrl = new URL(“”);

// 打開連接

HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();   

// 設置是否向connection輸出,因為這個是post請求,參數要放在

// http正文內,因此需要設為true

connection.setDoOutput(true);

// Read from the connection. Default is true.

connection.setDoInput(true);

// 默認是 GET方式

connection.setRequestMethod(“POST”);   

// Post 請求不能使用緩存

connection.setUseCaches(false);

//設置本次連接是否自動重定向

connection.setInstanceFollowRedirects(true);   

// 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的

// 意思是正文是urlencoded編碼過的form參數

connection.setRequestProperty(“Content-Type”,”application/x-www-form-urlencoded”);

// 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,

// 要注意的是connection.getOutputStream會隱含的進行connect。

connection.connect();

DataOutputStream out = new DataOutputStream(connection

.getOutputStream());

// 正文,正文內容其實跟get的URL中 ‘? ‘後的參數字符串一致

String content = “字段名=” + URLEncoder.encode(“字符串值”, “編碼”);

// DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫到流裡面

out.writeBytes(content);

//流用完記得關

out.flush();

out.close();

//獲取響應

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line;

while ((line = reader.readLine()) != null){

System.out.println(line);

}

reader.close();

//該乾的都幹完了,記得把連接斷了

connection.disconnect();

}

擴展資料:

關於Java HttpURLConnection使用

public static String sendPostValidate(String serviceUrl, String postData, String userName, String password){

PrintWriter out = null;

BufferedReader in = null;

String result = “”;

try {

log.info(“POST接口地址:”+serviceUrl);

URL realUrl = new URL(serviceUrl);

// 打開和URL之間的連接

URLConnection conn = realUrl.openConnection();

HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;

// 設置通用的請求屬性

httpUrlConnection.setRequestProperty(“accept”,”*/*”);

httpUrlConnection.setRequestProperty(“connection”, “Keep-Alive”);

httpUrlConnection.setRequestProperty(“user-agent”,”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);

httpUrlConnection.setRequestMethod(“POST”);

httpUrlConnection.setRequestProperty(“Content-Type”,”application/json;charset=UTF-8″);

Base64 base64 = new Base64();

String encoded = base64.encodeToString(new String(userName+ “:” +password).getBytes());

httpUrlConnection.setRequestProperty(“Authorization”, “Basic “+encoded);

// 發送POST請求必須設置如下兩行

httpUrlConnection.setDoOutput(true);

httpUrlConnection.setDoInput(true);

// 獲取URLConnection對象對應的輸出流

out = new PrintWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream(),”utf-8″));

// 發送請求參數

out.print(postData);

out.flush();

// 定義BufferedReader輸入流來讀取URL的響應

in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(),”utf-8″));

String line;

while ((line = in.readLine()) != null) {

result += line;

}

//         

//            if (!””.equals(result)) {

//                BASE64Decoder decoder = new BASE64Decoder();

//                try {

//                    byte[] b = decoder.decodeBuffer(result);

//                    result = new String(b, “utf-8”);

//                } catch (Exception e) {

//                    e.printStackTrace();

//                }

//            }

return result;

} catch (Exception e) {

log.info(“調用異常”,e);

throw new RuntimeException(e);

}

//使用finally塊來關閉輸出流、輸入流

finally{

try{

if(out!=null){

out.close();

}

if(in!=null){

in.close();

}

}

catch(IOException e){

log.info(“關閉流異常”,e);

}

}

}

}

如何使用java模擬post請求

/**

     * 向指定 URL 發送POST方法的請求

     * 

     * @param url

     *            發送請求的 URL

     * @param param

     *            請求參數,請求參數應該是 name1=value1name2=value2 的形式。

     * @return 所代表遠程資源的響應結果

     */

    public static String sendPost(String url, String param) {

        PrintWriter out = null;

        BufferedReader in = null;

        String result = “”;

        try {

            URL realUrl = new URL(url);

            // 打開和URL之間的連接

            URLConnection conn = realUrl.openConnection();

            // 設置通用的請求屬性

            conn.setRequestProperty(“accept”, “*/*”);

            conn.setRequestProperty(“connection”, “Keep-Alive”);

            conn.setRequestProperty(“user-agent”,

                    “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);

            // 發送POST請求必須設置如下兩行

            conn.setDoOutput(true);

            conn.setDoInput(true);

            // 獲取URLConnection對象對應的輸出流

            out = new PrintWriter(conn.getOutputStream());

            // 發送請求參數

            out.print(param);

            // flush輸出流的緩衝

            out.flush();

            // 定義BufferedReader輸入流來讀取URL的響應

            in = new BufferedReader(

                    new InputStreamReader(conn.getInputStream()));

            String line;

            while ((line = in.readLine()) != null) {

                result += line;

            }

        } catch (Exception e) {

            System.out.println(“發送 POST 請求出現異常!”+e);

            e.printStackTrace();

        }

        //使用finally塊來關閉輸出流、輸入流

        finally{

            try{

                if(out!=null){

                    out.close();

                }

                if(in!=null){

                    in.close();

                }

            }

            catch(IOException ex){

                ex.printStackTrace();

            }

        }

        return result;

    }

java中怎樣用post,get,put請求

java中用post,get,put請求方法:

public static String javaHttpGet(String url,String charSet){

String resultData = null;

try {

URL pathUrl = new URL(url); //創建一個URL對象

HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection(); //打開一個HttpURLConnection連接

urlConnect.setConnectTimeout(30000); // 設置連接超時時間

urlConnect.connect();

if (urlConnect.getResponseCode() == 200) { //請求成功

resultData = readInputStream(urlConnect.getInputStream(), charSet);

}

} catch (MalformedURLException e) {

LogL.getInstance().getLog().error(“URL出錯!”, e);

} catch (IOException e) {

LogL.getInstance().getLog().error(“讀取數據流出錯!”, e);

}

return resultData;

}

public static String javaHttpPost(String url,MapString,Object map,String charSet){

String resultData=null;

StringBuffer params = new StringBuffer();

try {

IteratorEntryString, Object ir = map.entrySet().iterator();

while (ir.hasNext()) {

Map.EntryString, Object entry = (Map.EntryString, Object) ir.next();

params.append(URLEncoder.encode(entry.getKey(),charSet) + “=” + URLEncoder.encode(entry.getValue().toString(), charSet) + “”);

}

byte[] postData = params.deleteCharAt(params.length()).toString().getBytes();

URL pathUrl = new URL(url); //創建一個URL對象

HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection();

urlConnect.setConnectTimeout(30000); // 設置連接超時時間

urlConnect.setDoOutput(true); //post請求必須設置允許輸出

urlConnect.setUseCaches(false); //post請求不能使用緩存

urlConnect.setRequestMethod(“POST”); //設置post方式請求

urlConnect.setInstanceFollowRedirects(true);

urlConnect.setRequestProperty(“Content-Type”,”application/x-www-form-urlencoded; charset=”+charSet);// 配置請求Content-Type

urlConnect.connect(); // 開始連接

DataOutputStream dos = new DataOutputStream(urlConnect.getOutputStream()); // 發送請求參數

dos.write(postData);

dos.flush();

dos.close();

if (urlConnect.getResponseCode() == 200) { //請求成功

resultData = readInputStream(urlConnect.getInputStream(),charSet);

}

} catch (MalformedURLException e) {

LogL.getInstance().getLog().error(“URL出錯!”, e);

} catch (IOException e) {

LogL.getInstance().getLog().error(“讀取數據流出錯!”, e);

} catch (Exception e) {

LogL.getInstance().getLog().error(“POST出錯!”, e);

}

return resultData;

}

原創文章,作者:RDQD,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/143051.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
RDQD的頭像RDQD
上一篇 2024-10-14 18:44
下一篇 2024-10-14 18:44

相關推薦

  • Python簡單數學計算

    本文將從多個方面介紹Python的簡單數學計算,包括基礎運算符、函數、庫以及實際應用場景。 一、基礎運算符 Python提供了基礎的算術運算符,包括加(+)、減(-)、乘(*)、除…

    編程 2025-04-29
  • Python滿天星代碼:讓編程變得更加簡單

    本文將從多個方面詳細闡述Python滿天星代碼,為大家介紹它的優點以及如何在編程中使用。無論是剛剛接觸編程還是資深程序員,都能從中獲得一定的收穫。 一、簡介 Python滿天星代碼…

    編程 2025-04-29
  • Python海龜代碼簡單畫圖

    本文將介紹如何使用Python的海龜庫進行簡單畫圖,並提供相關示例代碼。 一、基礎用法 使用Python的海龜庫,我們可以控制一個小海龜在窗口中移動,並利用它的“畫筆”在窗口中繪製…

    編程 2025-04-29
  • Python櫻花樹代碼簡單

    本文將對Python櫻花樹代碼進行詳細的闡述和講解,幫助讀者更好地理解該代碼的實現方法。 一、簡介 櫻花樹是一種圖形效果,它的實現方法比較簡單。Python中可以通過turtle這…

    編程 2025-04-28
  • Python大神作品:讓編程變得更加簡單

    Python作為一種高級的解釋性編程語言,一直被廣泛地運用於各個領域,從Web開發、遊戲開發到人工智能,Python都扮演着重要的角色。Python的代碼簡潔明了,易於閱讀和維護,…

    編程 2025-04-28
  • 用Python實現簡單爬蟲程序

    在當今時代,互聯網上的信息量是爆炸式增長的,其中很多信息可以被利用。對於數據分析、數據挖掘或者其他一些需要大量數據的任務,我們可以使用爬蟲技術從各個網站獲取需要的信息。而Pytho…

    編程 2025-04-28
  • 如何製作一個簡單的換裝遊戲

    本文將從以下幾個方面,為大家介紹如何製作一個簡單的換裝遊戲: 1. 遊戲需求和界面設計 2. 使用HTML、CSS和JavaScript開發遊戲 3. 實現遊戲的基本功能:拖拽交互…

    編程 2025-04-27
  • Guava Limiter——限流器的簡單易用

    本文將從多個維度對Guava Limiter進行詳細闡述,介紹其定義、使用方法、工作原理和案例應用等方面,並給出完整的代碼示例,希望能夠幫助讀者更好地了解和使用該庫。 一、定義 G…

    編程 2025-04-27
  • 2的32次方-1:一個看似簡單卻又複雜的數字

    對於計算機領域的人來說,2的32次方-1(也就是十進制下的4294967295)這個數字並不陌生。它經常被用來表示IPv4地址或者無符號32位整數的最大值。但實際上,這個數字卻包含…

    編程 2025-04-27
  • 製作一個簡單的管理系統的成本及實現

    想要製作一個簡單的管理系統,需要進行技術選型、開發、測試等過程,那麼這個過程會花費多少錢呢?我們將從多個方面來闡述製作一個簡單的管理系統的成本及實現。 一、技術選型 當我們開始思考…

    編程 2025-04-27

發表回復

登錄後才能評論