當前位置:首頁 » 編程語言 » java發送post請求

java發送post請求

發布時間: 2023-09-04 14:03:04

1. 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("http://www.xxxxxxx.com");

// 打開連接

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

}

(1)java發送post請求擴展閱讀:

關於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);

}

}

}

}

2. java調用post請求到localhost:4040

打包成jar就別用localhost了,改成伺服器的ip地址

3. java中get請求和post請求分別請求的對象類型是什麼,什麼不一樣

1. get 是從伺服器上獲取數據,post 是向伺服器傳送數據。 get 請求返回 request - URI 所指出的任意信息。
Post 請求用來發送電子郵件、新聞或發送能由交互用戶填寫的表格。這是唯一需要在請求中發送body的請求。使用Post請求時需要在報文首部 Content - Length 欄位中指出body的長度。
2. get 是把參數數據隊列加到提交表單的ACTION屬性所指的URL中,值和表單內各個欄位一一對應,在URL中可以乎吵看到。post是通過HTTP post機制纖頃尺,將表單內各個欄位與其內容放置在HTML HEADER內一起傳送到ACTION屬性所指的URL地址,用戶看不到這個過程。
3. 對於 get 方式,伺服器端用Request.QueryString獲取變數的值,對於 post 方式,伺服器端用Request.Form獲取提交的數據。
4. get 傳送的數據量較小,不能大於2KB。post 傳送的數據量較大,一般被默認為不受限制。但理論上,IIS4中最大量為80KB,IIS5中為100KB。 用IIS過濾器的只接受get參數,所以一般大型搜索引擎都是用get方式。
5. get 安全性非常低,post 安全性相對較高。如果這些數據是中毀高文數據而且是非敏感數據,那麼使用 get;如果用戶輸入的數據不是中文字元而且包含敏感數據,那麼還是使用 post 為好。

4. 如何使用java發送post請求

/**
* 向指定 URL 發送POST方法的請求
*
* @param url
* 發送請求的 URL
* @param param
* 請求參數,請求參數應該是 name1=value1&name2=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;
}

5. Java利用HttpURLConnection發送post請求上傳文件

在頁面里實現上傳文件不是什麼難事 寫個form 加上enctype = multipart/form data 在寫個接收的就可以了 沒租褲什麼難的 如果要用 HttpURLConnection來實現文件上傳 還真有點搞頭 : )

先寫個servlet把接收到的 HTTP 信息保存在一個文件中 看一下 form 表單到底封裝了什麼樣的信息

Java代碼

public void doPost(HttpServletRequest request HttpServletResponse response)

throws ServletException IOException {

//獲取輸入流 是HTTP協議中的實體內容

ServletInputStream in=request getInputStream();

//緩沖區

byte buffer[]=new byte[ ];

FileOutputStream out=new FileOutputStream( d:\test log );

int len=sis read(buffer );

//把流里的信息循環讀入到file log文件中

while( len!= ){

out write(buffer len);

len=in readLine(buffer );

}

out close();

in close();

}

來一個form表單

<form name= upform action= upload do method= POST

enctype= multipart/form data >

參數<input type= text name= username /><br/>

文件 <input type= file name= file /><br/>

文件 <input type= file name= file /><br/>

<input type= submit value= Submit />

<br />

</form>

假如我參數寫的內容是hello word 然後二個文件是二個簡單的txt文件梁譽 上傳後test log里如下

Java代碼

da e c

Content Disposition: form data; name= username

hello word

da e c

Content Disposition: form data; name= file ; filename= D:haha txt

Content Type: text/plain

haha

hahaha

da e c

Content Disposition: form data; name= file ; filename= D:huhu txt

Content Type: text/plain

messi

huhu

da e c

研究下規律發現有如下幾點特徵

第一行是 d b bc 作為分隔符 然後是 回車換行符 這個 d b bc 分隔符瀏覽器是隨機生成的

第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=對應input的name值 filename對應要上傳的文件名(包括路徑在內)

第三行如果是文件就有Content Type: text/plain 這里上傳的是txt文件所以是text/plain 如果上穿的是jpg圖片的話就是image/jpg了 可以自己試試看看

然後就是回弊渣簡車換行符

在下就是文件或參數的內容或值了 如 hello word

最後一行是 da e c 注意最後多了二個 ;

有了這些就可以使用HttpURLConnection來實現上傳文件功能了

Java代碼 public void upload(){

List<String> list = new ArrayList<String>(); //要上傳的文件名 如 d:haha doc 你要實現自己的業務 我這里就是一個空list

try {

String BOUNDARY = d a d c ; // 定義數據分隔線

URL url = new URL( );

HttpURLConnection conn = (HttpURLConnection) url openConnection();

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

conn setDoOutput(true);

conn setDoInput(true);

conn setUseCaches(false);

conn setRequestMethod( POST );

conn setRequestProperty( connection Keep Alive );

conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );

conn setRequestProperty( Charsert UTF );

conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);

OutputStream out = new DataOutputStream(conn getOutputStream());

byte[] end_data = ( + BOUNDARY + ) getBytes();// 定義最後數據分隔線

int leng = list size();

for(int i= ;i<leng;i++){

String fname = list get(i);

File file = new File(fname);

StringBuilder *** = new StringBuilder();

*** append( );

*** append(BOUNDARY);

*** append( );

*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );

*** append( Content Type:application/octet stream );

byte[] data = *** toString() getBytes();

out write(data);

DataInputStream in = new DataInputStream(new FileInputStream(file));

int bytes = ;

byte[] bufferOut = new byte[ ];

while ((bytes = in read(bufferOut)) != ) {

out write(bufferOut bytes);

}

out write( getBytes()); //多個文件時 二個文件之間加入這個

in close();

}

out write(end_data);

out flush();

out close();

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

BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));

String line = null;

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

System out println(line);

}

} catch (Exception e) {

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

e printStackTrace();

}

lishixin/Article/program/Java/hx/201311/27114

熱點內容
滑板鞋腳本視頻 發布:2025-02-02 09:48:54 瀏覽:433
群暉怎麼玩安卓模擬器 發布:2025-02-02 09:45:23 瀏覽:557
三星安卓12彩蛋怎麼玩 發布:2025-02-02 09:44:39 瀏覽:744
電腦顯示連接伺服器錯誤 發布:2025-02-02 09:24:10 瀏覽:537
瑞芯微開發板編譯 發布:2025-02-02 09:22:54 瀏覽:147
linux虛擬機用gcc編譯時顯示錯誤 發布:2025-02-02 09:14:01 瀏覽:240
java駝峰 發布:2025-02-02 09:13:26 瀏覽:652
魔獸腳本怎麼用 發布:2025-02-02 09:10:28 瀏覽:538
linuxadobe 發布:2025-02-02 09:09:43 瀏覽:212
sql2000資料庫連接 發布:2025-02-02 09:09:43 瀏覽:726