簡體   English   中英

有沒有辦法在沒有外部庫的情況下通過NetBeans發送GET和POST請求?

[英]Is there a way to send GET and POST requests via NetBeans without an external library?

我最近選擇了NetBeans,它看起來像是用於編寫GUI應用程序的綜合IDE。 讓我感到與眾不同的是,它沒有任何內置的支持來創建和讀取對簡單GET和POST請求的響應。 盡管這似乎是因為它針對的是對使用NetBeans編寫Web服務感興趣的人群,但我希望該程序中將具有一些基本的請求和響應功能。

是否已經包含一個圖書館來滿足此目的? (如果存在,我必須使用錯誤的方法來查找它。)

目前,我已經下載並使用了Apache的HTTPClient和IOUtils,它們雖然有效,但看起來可能是多余的。

試試看
對於GET

URL url = new URL(urlString);
HttpURLConnection c = (HttpURLConnection)url.openConnection();  //connecting to url
c.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));  //stream to resource
String str;
while ((str = in.readLine()) != null)   //reading data
   responsestring += str+"\n";//process the response and save it in some string or so
in.close();  //closing stream

對於POST

URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

con.setRequestMethod("POST");

String urlParameters = ..;

con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer res = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    res.append(inputLine);
}
in.close();

NetBeans不為您提供任何Java類。 所有類均來自Java庫,NetBeans只是一個IDE,可讓您方便地完成工作。

因此,要翻譯您的問題:不,除了URLConnection之外,標准Java庫沒有為您提供有用的http客戶端。

Apache HTTPClient庫是一種很好的方法,盡管適用於基本的GET和POST,但它太復雜了。 自己編寫GET和POST的代碼非常容易,不過,請看一下htt協議

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM