當前位置:首頁 » 文件管理 » javahttp上傳圖片

javahttp上傳圖片

發布時間: 2025-03-10 13:39:56

㈠ 如何來 發送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 web客戶端上傳圖片到伺服器的D盤下,請問客戶端怎麼通過http訪問圖片

如果想讓tomcat伺服器訪問指定磁碟 上的靜態資源,可在tomcat/conf/server.xml中查找<Host></Host>,在標簽中添加如下標簽<Context path="/file" docBase="D:/img" reloadable="true"/>,再通過localhost:8080/file地址來訪問路境內的文件:
如要訪問名為d:/img/cat.png的圖片,則localhost:8080/file/cat.png

㈢ java http post 怎麼設置 raw格式

調試微信推廣支持中二維碼生成api的介面,使用chrome瀏覽器的postman插件,post請求時有一個選項是form-data,或者raw,使用raw可以請求成功,from-data不知道怎麼組裝key和value所以一直失敗。非常不明白raw是什麼意思,google網路都沒有相關的解釋。後來研究發現,其實raw方式使用的是純字元串的數據上傳方式,所以在POST之前,可能需要手工的把一些json/text/xml格式的數據轉換成字元串,是一種post原始請求,區別於form-data這種常用的key-value方式。
public static String result; public static void httpTest() throws ClientProtocolException, IOException { String token = "XRhjxAJZG3rFlPLg"; String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token; String json = "{"action_name":"QR_LIMIT_SCENE","action_info":{"scene":{"scene_id":234}}}"; HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); StringEntity postingString = new StringEntity(json);// json傳遞 post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(post); String content = EntityUtils.toString(response.getEntity()); // Log.i("test",content); System.out.println(content); result = content; }

以上代碼中需要導入

import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;

Android中自帶org.apache.http相關庫文件,所以可以快捷鍵(ctrl+shift+o)一次導入成功。

㈣ 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

㈤ 用JAVA下載HTTP文件時遇到問題

importjava.net.*;
importjava.io.*;
publicclassURLConnectionDemo{
publicstaticvoidmain(String[]args)throwsException{
URLurl=newURL("http://www.scp.e.cn/pantoschoolzz/BG/Bord/Message/DownloadMessageAttachment.aspx?ID=215");
URLConnectionuc=url.openConnection();
StringfileName=uc.getHeaderField(6);
fileName=URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
System.out.println("文件名為:"+fileName);
System.out.println("文件大小:"+(uc.getContentLength()/1024)+"KB");
Stringpath="D:"+File.separator+fileName;
FileOutputStreamos=newFileOutputStream(path);
InputStreamis=uc.getInputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=is.read(b))!=-1){
os.write(b,0,len);
}
os.close();
is.close();
System.out.println("下載成功,文件保存在:"+path);
}
}

//給你一個下載的例子吧,僅供參考。

熱點內容
柚子游戲伺服器搭建教程 發布:2025-03-10 17:11:02 瀏覽:559
中信銀行電子令牌密碼是什麼 發布:2025-03-10 17:10:20 瀏覽:316
阿里伺服器雲盤丟失 發布:2025-03-10 17:09:32 瀏覽:94
熱雲伺服器 發布:2025-03-10 17:02:36 瀏覽:994
cpp1新建編譯 發布:2025-03-10 17:00:14 瀏覽:226
走水標高演算法 發布:2025-03-10 17:00:07 瀏覽:787
伺服器更新地址之後登錄不上 發布:2025-03-10 16:36:29 瀏覽:706
資料庫前端 發布:2025-03-10 16:23:47 瀏覽:417
當腳本運行後 發布:2025-03-10 16:18:50 瀏覽:845
如何確認自己的手機型號安卓 發布:2025-03-10 16:11:31 瀏覽:23