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

post請求java

發布時間: 2022-09-06 16:23:32

⑴ 如何使用java模擬post請求

兩種選擇:一、使用httpclient,二使用java自帶的類庫。
1、java自帶類庫:

public static String call(String address,String params) {

URL url = null;

HttpURLConnection httpurlconnection = null;

StringBuilder result = new StringBuilder();

try {

url = new URL(address);

// 以post方式請求

httpurlconnection = (HttpURLConnection) url.openConnection();

httpurlconnection.setDoOutput(true);

httpurlconnection.setRequestMethod("POST");

if(null!=params&¶ms.length()>0){

httpurlconnection.getOutputStream().write(params.getBytes());

httpurlconnection.getOutputStream().flush();

httpurlconnection.getOutputStream().close();

}

// 獲取頁面內容

java.io.InputStream in = httpurlconnection.getInputStream();

java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in, Config.DEFAULT_CHARSET));

String str = breader.readLine();

while (str != null) {

result.append(str);

str = breader.readLine();

}

breader.close();

in.close();

} catch (Exception e) {

} finally {

if (httpurlconnection != null)

httpurlconnection.disconnect();

}

return result.toString().trim();

}

2、httpclient:

public static String post(String url,String params){
HttpClient httpClient = new DefaultHttpClient();

StringBuilder builder = new StringBuilder();

HttpPost post = new HttpPost(url);

try {

if(null!=params){

post.setEntity(new StringEntity(params,"UTF-8"));

}

HttpResponse resp = httpClient.execute(post);

int statusCode = resp.getStatusLine().getStatusCode();

if(statusCode<=304){

HttpEntity entity = resp.getEntity();

if (entity == null) {

throw new IllegalArgumentException("HTTP entity may not be null");

}

if (entity.getContentLength() > Integer.MAX_VALUE) {

throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");

}

int i = (int)entity.getContentLength();

i = i<0 ? 4096 : i;

final InputStream instream = entity.getContent();

final Reader reader = new InputStreamReader(instream, Config.DEFAULT_CHARSET);

final CharArrayBuffer buffer = new CharArrayBuffer(i);

final char[] tmp = new char[1024];

int l;

while((l = reader.read(tmp)) != -1) {

buffer.append(tmp, 0, l);

}

builder.append(buffer);

}

post.abort();

} catch (Exception e) {

post.abort();

}

return builder.toString().trim();

}

⑵ Java sendPost請求方法如何加入參數

/**
* 向指定 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;
}

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

}

(3)post請求java擴展閱讀:

關於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=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;
}

⑸ 如何在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){
List<NameValuePair> nvps= new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("id", "1"));
String url="https://www.hao123.com/";

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中Get和Post請求的區別收集整理

Get:是以實體的方式得到由請求URI所指定資源的信息,如果請求URI只是一個數據產生過程,那麼最終要在響應實體中返回的是處理過程的結果所指向的資源,而不是處理過程的描述。
Post:用來向目的伺服器發出請求,要求它接受被附在請求後的實體,並把它當作請求隊列中請求URI所指定資源的附加新子項,Post被設計成用統一的方法實現下列功能:
1:對現有資源的解釋
2:向電子公告欄、新聞組、郵件列表或類似討論組發信息。
3:提交數據塊
4:通過附加操作來擴展資料庫
從上面描述可以看出,Get是向伺服器發索取數據的一種請求;而Post是向伺服器提交數據的一種請求,要提交的數據位於信息頭後面的實體中。

⑺ java調用post請求到localhost:4040

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

⑻ java post請求相關

需要什麼請求什麼就可以,登錄認證信息是放在session中的,看你是用什麼安全認證框架,還是手寫filter判斷用戶是否認證通過,然後返回對應的資源,沒通過認證就跳到登錄

⑼ 怎麼使用java模擬post請求

你要導入httpclient的jar包,要是你請求參數格式是json的或者返回的是json格式數據,你還需要導入json包
/**
* post請求
* @param url url地址
* @param jsonParam 參數
* @param noNeedResponse 不需要返回結果
* @return
*/
public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
//post請求返回結果
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonResult = null;

熱點內容
ios應用上傳 發布:2024-09-08 09:39:41 瀏覽:438
ios儲存密碼哪裡看 發布:2024-09-08 09:30:02 瀏覽:869
opensslcmake編譯 發布:2024-09-08 09:08:48 瀏覽:653
linux下ntp伺服器搭建 發布:2024-09-08 08:26:46 瀏覽:744
db2新建資料庫 發布:2024-09-08 08:10:19 瀏覽:173
頻率計源碼 發布:2024-09-08 07:40:26 瀏覽:780
奧迪a6哪個配置帶後排加熱 發布:2024-09-08 07:06:32 瀏覽:101
linux修改apache埠 發布:2024-09-08 07:05:49 瀏覽:209
有多少個不同的密碼子 發布:2024-09-08 07:00:46 瀏覽:566
linux搭建mysql伺服器配置 發布:2024-09-08 06:50:02 瀏覽:995