javapost,javapost方法

本文目錄一覽:

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;

}

如何在java中發送post請求

package com.test;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

public class D {

public static void main(String[] args){

ListNameValuePair nvps= new ArrayListNameValuePair();

nvps.add(new BasicNameValuePair(“id”, “1”));

String url=””;

HttpClient httpClient = null;

String response=””;

try {

HttpPost post = new HttpPost(url);

post.setHeader(“Connection”, “close”);

httpClient = new DefaultHttpClient();

post.setEntity(new UrlEncodedFormEntity(nvps));

HttpResponse httpres= httpClient.execute(post);

if (httpres.getStatusLine().getStatusCode() = 300) {

System.out.println(“Request Failed,Code:” + httpres.getStatusLine().getStatusCode() + “,URL:” + url);

}

response = EntityUtils.toString(httpres.getEntity(), “utf-8”);

}catch(Exception e){

e.printStackTrace();

}finally{

if(httpClient!=null){

httpClient.getConnectionManager().shutdown();

}

}

System.out.println(response);

}

}

需要httpclient-4.1.3.jar,httpcore-4.1.4.jar和commons-logging-1.1.1.jar

如何使用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 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);

}

}

}

}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/151623.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-11 13:43
下一篇 2024-11-11 13:43

相關推薦

  • 解決.net 6.0運行閃退的方法

    如果你正在使用.net 6.0開發應用程序,可能會遇到程序閃退的情況。這篇文章將從多個方面為你解決這個問題。 一、代碼問題 代碼問題是導致.net 6.0程序閃退的主要原因之一。首…

    編程 2025-04-29
  • ArcGIS更改標註位置為中心的方法

    本篇文章將從多個方面詳細闡述如何在ArcGIS中更改標註位置為中心。讓我們一步步來看。 一、禁止標註智能調整 在ArcMap中設置標註智能調整可以自動將標註位置調整到最佳顯示位置。…

    編程 2025-04-29
  • Python中init方法的作用及使用方法

    Python中的init方法是一個類的構造函數,在創建對象時被調用。在本篇文章中,我們將從多個方面詳細討論init方法的作用,使用方法以及注意點。 一、定義init方法 在Pyth…

    編程 2025-04-29
  • Python創建分配內存的方法

    在python中,我們常常需要創建並分配內存來存儲數據。不同的類型和數據結構可能需要不同的方法來分配內存。本文將從多個方面介紹Python創建分配內存的方法,包括列表、元組、字典、…

    編程 2025-04-29
  • 用不同的方法求素數

    素數是指只能被1和自身整除的正整數,如2、3、5、7、11、13等。素數在密碼學、計算機科學、數學、物理等領域都有著廣泛的應用。本文將介紹幾種常見的求素數的方法,包括暴力枚舉法、埃…

    編程 2025-04-29
  • 使用Vue實現前端AES加密並輸出為十六進位的方法

    在前端開發中,數據傳輸的安全性問題十分重要,其中一種保護數據安全的方式是加密。本文將會介紹如何使用Vue框架實現前端AES加密並將加密結果輸出為十六進位。 一、AES加密介紹 AE…

    編程 2025-04-29
  • Python中讀入csv文件數據的方法用法介紹

    csv是一種常見的數據格式,通常用於存儲小型數據集。Python作為一種廣泛流行的編程語言,內置了許多操作csv文件的庫。本文將從多個方面詳細介紹Python讀入csv文件的方法。…

    編程 2025-04-29
  • Python學習筆記:去除字元串最後一個字元的方法

    本文將從多個方面詳細闡述如何通過Python去除字元串最後一個字元,包括使用切片、pop()、刪除、替換等方法來實現。 一、字元串切片 在Python中,可以通過字元串切片的方式來…

    編程 2025-04-29
  • 用法介紹Python集合update方法

    Python集合(set)update()方法是Python的一種集合操作方法,用於將多個集合合併為一個集合。本篇文章將從以下幾個方面進行詳細闡述: 一、參數的含義和用法 Pyth…

    編程 2025-04-29
  • Vb運行程序的三種方法

    VB是一種非常實用的編程工具,它可以被用於開發各種不同的應用程序,從簡單的計算器到更複雜的商業軟體。在VB中,有許多不同的方法可以運行程序,包括編譯器、發布程序以及命令行。在本文中…

    編程 2025-04-29

發表回復

登錄後才能評論