當前位置:首頁 » 編程語言 » httppostjava

httppostjava

發布時間: 2025-09-21 09:11:28

『壹』 如何使用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模擬瀏覽器提交html頁面的表單數據

httpclient就行了,給你個取IP的例子好了

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class IPHelper {

public String getSourceText(String ip) throws IOException {
String text = null;
HttpClient client = new HttpClient();
client.getParams().setContentCharset("GBK");
PostMethod post = new PostMethod("http://www.ip138.com/ips8.asp");
NameValuePair[] data = { new NameValuePair("action", "2"),
new NameValuePair("ip", ip) };
post.setRequestBody(data);
client.executeMethod(post);
text = post.getResponseBodyAsString();
post.releaseConnection();
return text;
}

public static void main(String[] args) throws IOException {
IPHelper h=new IPHelper();
System.out.println(h.getSourceText("192.169.0.1"));
}
}

這個是Post的,還有Get的,看你的form是怎麼樣的了。

『叄』 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)httppostjava擴展閱讀:

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

}

}

}

}

『肆』 如何來 發送HTTP請求GET / POST在Java中

在Java中發送HTTP請求,主要涉及到請求行的構建。請求行由三個部分組成:請求方法欄位、URL欄位和HTTP協議版本欄位,這三個欄位之間用空格分隔。例如,使用GET方法訪問某個HTML頁面時,請求行可以表示為"GET /index.html HTTP/1.1"。這里,"GET"是請求方法,"/index.html"是訪問的資源路徑,而"HTTP/1.1"則指定了使用的HTTP版本。

除了GET方法外,HTTP協議還支持其他幾種請求方法,包括POST、HEAD、PUT、DELETE、OPTIONS、TRACE和CONNECT。其中,POST方法通常用於向伺服器發送數據,例如提交表單或上傳文件;而HEAD方法則只獲取響應頭,不獲取響應體;PUT方法用於上傳數據到伺服器,相當於文件上傳;DELETE方法則是用於刪除伺服器上的資源;OPTIONS方法用於獲取伺服器的許可信息,如支持的請求方法;TRACE方法用於回顯客戶端發送的請求,主要用於診斷;而CONNECT方法則是用於建立代理連接。

Java中發送HTTP請求的方法有很多,比如使用HttpURLConnection類或第三方庫如Apache HttpClient和OkHttp。以HttpURLConnection為例,首先需要創建一個URL對象,然後通過該對象獲取HttpURLConnection實例,接下來設置請求方法、添加請求頭等,最後執行請求並獲取響應。而使用第三方庫時,初始化和設置則更加靈活,可以根據需求選擇合適的庫進行操作。

對於GET請求,HttpURLConnection的使用相對簡單。以下是一個使用HttpURLConnection發送GET請求的例子:

java

URL url = new URL("http://example.com/index.html");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("Failed : HTTP error code : " + responseCode);
}

通過這段代碼,你可以看到如何通過HttpURLConnection發送GET請求並處理響應。當然,實際應用中可能還需要處理更復雜的情況,比如添加請求頭、處理異常等。

對於POST請求,基本步驟類似,只是需要設置請求方法為POST,並且通常需要設置請求體。以下是一個簡單的POST請求示例:

java

URL url = new URL("http://example.com/post");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data = "param1=value1¶m2=value2";
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(data);
}

這段代碼展示了如何通過HttpURLConnection發送POST請求,並設置請求體。同樣,實際應用中可能需要添加更多細節,如處理響應、添加更多請求頭等。

總之,Java中發送HTTP請求GET和POST方法的實現方式多樣,可以根據具體需求選擇合適的庫和方法。無論使用哪種方式,都需要正確設置請求方法、URL、請求頭等,才能確保請求的成功發送和響應的正確處理。

『伍』 java 介面調用,根據介面文檔寫測試,用post方法,剛怎麼做啊,有個完整的例子么

可使用android自帶的httpclient框架實現。

1. GET 方式傳遞參數
//先將參數放入List,再對參數進行URL編碼
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "數據")); //增加參數1
params.add(new BasicNameValuePair("param2", "value2"));//增加參數2
String param = URLEncodedUtils.format(params, "UTF-8");//對參數編碼
String baseUrl = "伺服器介面完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//將URL與參數拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //發起GET請求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取伺服器響應內容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

2. POST方式 方式傳遞參數
//和GET方式一樣,先將參數放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加參數1
params.add(new BasicNameValuePair("param2", "第二個參數"));//增加參數2
try {
HttpPost postMethod = new HttpPost(baseUrl);//創建一個post請求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //執行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

『陸』 java http post 同時發送文件流與數據

您好,提問者:
首先表單、文件同時發送那麼肯定是可以的,關於獲取的話很難了,因為發送文件的話form必須設置為:multipart/form-data數據格式,默認為:application/x-www-form-urlencoded表單格式。我們稱之為二進制流和普通數據流。

剛才說了<form的entype要改為multipart/form-data才能進行發送文件,那麼這個時候你表單的另外數據就也會被當成二進制一起發送到服務端。

獲取讀取過來的內容如下:

//拿到用戶傳送過來的位元組流
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}

上面如圖的代碼,我們發現發送過來的表單數據跟文件數據是混亂的,我們根本沒辦法解析(很麻煩),這個時候我們就需要用到第三方輔助(apache 提供的fileupload.jar)來進行獲取。

這個網上有很多代碼的,如果有什麼不明白可以去自行網路,或者追問,我這里只是給你提供的思路,希望理解,謝謝!

熱點內容
恢復微軟默認激活伺服器地址 發布:2025-09-21 11:03:01 瀏覽:37
阿里雲伺服器怎麼重置 發布:2025-09-21 10:53:11 瀏覽:109
c訪問hbase 發布:2025-09-21 10:42:09 瀏覽:215
java設計報告 發布:2025-09-21 10:32:40 瀏覽:646
tira壓縮 發布:2025-09-21 10:19:37 瀏覽:544
對講機頻道加密 發布:2025-09-21 10:17:01 瀏覽:879
刷視頻腳本編寫 發布:2025-09-21 10:05:38 瀏覽:339
linuxtargz解壓命令 發布:2025-09-21 10:05:28 瀏覽:455
企業網站雲伺服器怎麼選 發布:2025-09-21 10:05:28 瀏覽:733
二胎需要存儲臍帶血嗎 發布:2025-09-21 09:43:05 瀏覽:899