1. 程式人生 > >java模擬post傳輸檔案到tomcat伺服器端servlet接收

java模擬post傳輸檔案到tomcat伺服器端servlet接收

網路上一篇介紹這個的文章,如下文章1其實是有問題的。實際上它的模擬http請求的格式有點問題,如果傳輸.txt檔案就會發現.txt檔案裡面多出了一些字元,而這些字元是我們的傳輸檔案頭內容。為什麼會這樣的?

參考文章2我們對比發現文章1的傳輸檔案頭和檔案內容的組合格式有問題的,正確的應該是文章2的樣子,但是文章2又缺少了檔案尾。最後綜合之後,正確的格式應該是:


------------HV2ymHFg03ehbqgZCaKO6jyH
Content-Disposition: form-data; name="username"

Patrick
------------HV2ymHFg03ehbqgZCaKO6jyH
Content-Disposition: form-data; name="password"

HELLOPATRICK
------------HV2ymHFg03ehbqgZCaKO6jyH
Content-Disposition: form-data; name="hobby"

Computer programming
------------HV2ymHFg03ehbqgZCaKO6jyH

Content-Disposition:form-data; name="upload1"; filename="C:\123.txt"
Content-Type:application/octet-stream

------------HV2ymHFg03ehbqgZCaKO6jyH--

------------HV2ymHFg03ehbqgZCaKO6jyH

Content-Disposition:form-data; name="upload2"; filename="C:\Asturias.mp3"
Content-Type:application/octet-stream

------------HV2ymHFg03ehbqgZCaKO6jyH--

------------HV2ymHFg03ehbqgZCaKO6jyH

Content-Disposition:form-data; name="upload3"; filename="C:\dyz.txt"
Content-Type:application/octet-stream

------------HV2ymHFg03ehbqgZCaKO6jyH--

------------HV2ymHFg03ehbqgZCaKO6jyH

Content-Disposition:form-data; name="upload4"; filename="C:\full.jpg"
Content-Type:application/octet-stream

------------HV2ymHFg03ehbqgZCaKO6jyH--

------------HV2ymHFg03ehbqgZCaKO6jyH

Content-Disposition:form-data; name="upload5"; filename="C:\Recovery.txt"
Content-Type:application/octet-stream

------------HV2ymHFg03ehbqgZCaKO6jyH--

文章1

在某些情況下,需要用Java applicatioin來模擬form,向伺服器(本文以servlet為例)傳送http post請求,包括提交表單域中的資料以及上傳檔案。如果僅僅是傳遞form中的資料,而不包含上傳檔案,那是很簡單的,比如Java application可以這麼寫:

package com.pat.postrequestemulator;

importjava.io.BufferedReader;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjava.io.OutputStreamWriter;

importjava.net.HttpURLConnection;

importjava.net.URL;

public class PostRequestEmulator

{

         public static void main(String[] args)throws Exception

         {

                   // 服務地址

                   URL url = newURL("http://127.0.0.1:8080/test/upload");

                   // 設定連線的相關引數

                   HttpURLConnection connection= (HttpURLConnection) url.openConnection();

                   connection.setDoOutput(true);

                   connection.setRequestMethod("POST");

                   OutputStreamWriter out = newOutputStreamWriter(connection.getOutputStream(), "UTF-8");

                   // 向服務端傳送key = value對

                   out.write("username=kevin&password=pass");

                   out.flush();

                   out.close();

                   // 獲取服務端的反饋

                   String strLine="";

                   String strResponse ="";

                   InputStream in =connection.getInputStream();

                   BufferedReader reader = newBufferedReader(new InputStreamReader(in));

                   while((strLine =reader.readLine()) != null)

                   {

                            strResponse +=strLine +"\n";

                   }

                   System.out.print(strResponse);

         }

}

服務端的servlet可以這麼寫:

packagecom.pat.handlinghttprequestservlet;

importjava.io.IOException;

importjava.io.PrintWriter;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

public class HandlingHttpRequestServlet extends HttpServlet

{

         private static final longserialVersionUID = 1L;

         @Override

         protected void doGet(HttpServletRequestreq, HttpServletResponse resp)

         throws ServletException, IOException

         {

                   super.doGet(req, resp);

         }

         @Override

         protected void doPost(HttpServletRequest req, HttpServletResponse resp)

         throwsServletException, IOException

         {

                   String username =req.getParameter("username");          //獲取username所對應的value

                   String password =req.getParameter("password");           //獲取password所對應的value

                   System.out.println("Thereceived username and password is: " + username + "/" +password);

                   // 向請求端發回反饋資訊

                   PrintWriter out =resp.getWriter();

                   out.print("OK");

                   out.flush();

                   out.close();

                   super.doPost(req, resp);

         }

}

一切看起來都不復雜。但是如果要模擬的表單,除了要向伺服器傳遞如上面的“key = value”這樣的普通訊息,同時還要上傳檔案,事情就複雜得多。下面詳解如下:

1. 準備

玄機逸士很久沒有開發web方面的應用了,所以機器上沒有現成的環境,為此先要進行這方面的準備。

     如:D:\Tomcat6

     和commons-io-2.1-bin.zip, commons-fileupload依賴於commons-io,但在程式設計的過程中,

     不會直接用到commons-io

c)  檢查Tomcat的安裝是否成功。雙擊D:\Tomcat6\bin目錄中的startup.bat檔案,就可以啟動tomcat。

     開啟瀏覽器,訪問http://localhost:8080/,如果出現tomcat相關的頁面,則說明tomcat安裝成功。

d)  在D:\Tomcat6\webapps目錄下建立一個test子目錄,我們等會開發的servlet就將部署在這裡。在

     test目錄下再建立兩個目錄WEB-INF(必須大寫)和upload,在WEB-INF下面 建立兩個目錄classes和lib,

     同時新建一個web.xml檔案;在upload目錄下,建立一個temp子目錄,這些工作做完以後,test目錄

     下面的目錄檔案結構如下圖所示。


其中的classes目錄,用來存放將要開發的servlet,lib用來存放commons-fileupload和commons-io相關的jar包,web.xml是一些應用描述資訊;upload用於存放客戶端(即我們要開發的Java application)上傳過來的檔案,temp則用於存放上傳過程中可能產生的一些臨時檔案。

e)  將commons-fileupload-1.2.2-bin.zip和commons-io-2.1-bin.zip解壓,可以得到commons-fileupload-

     1.2.2.jar和commons-io-2.1.jar,我們將這兩個檔案拷貝到d)中建立的lib目錄中。

f)   編輯web.xml使之如下:

<?xmlversion="1.0" encoding="ISO-8859-1"?>

<!--

 Licensed to the Apache Software Foundation(ASF) under one or more

  contributor license agreements.  See the NOTICE file distributed with

  this work for additional informationregarding copyright ownership.

  The ASF licenses this file to You under theApache License, Version 2.0

  (the "License"); you may not usethis file except in compliance with

  the License. You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreedto in writing, software

  distributed under the License is distributedon an "AS IS" BASIS,

  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.

  See the License for the specific languagegoverning permissions and

  limitations under the License.

-->

<web-appxmlns="http://java.sun.com/xml/ns/javaee"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

   version="2.5">

   <servlet>

         <servlet-name>Hello</servlet-name>

          <servlet-class>com.pat.handlinghttprequestservlet.HandlingHttpRequestServlet</servlet-class>

    </servlet>

    <servlet-mapping>  

         <servlet-name>Hello</servlet-name>

         <url-pattern>/upload</url-pattern> 

    </servlet-mapping>

</web-app>

這個web.xml可以先從D:\Tomcat6\webapps\examples\WEB-INF下面拷貝過來,再進行如上黑體字所示的修改即可。<servlet>標籤描述的是servlet程式碼方面的資料,其中<servlet-name>Hello</servlet-name>是給這個servlet起一個名字Hello,它必須和下面的<servlet-mapping>中的<servlet-name>一致,該名字具體是什麼可以隨意寫定。

<servlet-class>com.pat.handlinghttprequestservlet.HandlingHttpRequestServlet</servlet-class>說明了完整的servlet類名,即servlet的類名為HandlingHttpRequestServlet,它位於包com.pat.handlinghttprequestservlet中。

<url-pattern>/upload</url-pattern>,說明了如果客戶端向“http://Web伺服器的URL地址:埠號/test/upload”發出了請求,則該請求將由位於包com.pat.handlinghttprequestservlet中的HandlingHttpRequestServlet進行處理。

到此,前期準備工作結束。下面準備寫程式碼。

2.       Servlet的程式碼

packagecom.pat.handlinghttprequestservlet;

importjava.io.File;

importjava.io.IOException;

importjava.io.PrintWriter;

importjava.util.ArrayList;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.commons.fileupload.FileItem;

importorg.apache.commons.fileupload.disk.DiskFileItemFactory;

importorg.apache.commons.fileupload.servlet.ServletFileUpload;

public class HandlingHttpRequestServlet extends HttpServlet

{

         private static final longserialVersionUID = 1L;

         @Override

         protected void doGet(HttpServletRequestreq, HttpServletResponse resp)

         throws ServletException, IOException

         {

                   super.doGet(req, resp);

         }

         @SuppressWarnings({"unchecked", "deprecation" })

         @Override

         protected void doPost(HttpServletRequest req, HttpServletResponse resp)

         throwsServletException, IOException

         {       

                   DiskFileItemFactory factory =new DiskFileItemFactory();

                   //得到絕對資料夾路徑,比如"D:\\Tomcat6\\webapps\\test\\upload"

                   String path = req.getRealPath("/upload");

                   //臨時資料夾路徑

                   String repositoryPath =req.getRealPath("/upload/temp");        

                   // 設定臨時資料夾為repositoryPath

                   factory.setRepository(newFile(repositoryPath)); 

                   // 設定上傳檔案的閾值,如果上傳檔案大於1M,就可能在repository

                   // 所代 表的資料夾中產生臨時檔案,否則直接在記憶體中進行處理

                   factory.setSizeThreshold(1024* 1024);

                   //System.out.println("----"+ req.getContextPath());  // 得到相對資料夾路徑,比如 "/test"

                   // 建立一個ServletFileUpload物件

                   ServletFileUpload uploader =new ServletFileUpload(factory);

                   try

                   {

                            // 呼叫uploader中的parseRequest方法,可以獲得請求中的相關內容,

                            // 即一個FileItem型別的ArrayList。FileItem是在

                            // org.apache.commons.fileupload中定義的,它可以代表一個檔案,

                            // 也可以代表一個普通的form field

                            ArrayList<FileItem>list = (ArrayList<FileItem>)uploader.parseRequest(req);

                            System.out.println(list.size());

                            for(FileItemfileItem : list)

                            {

                                     if(fileItem.isFormField())      // 如果是普通的form field

                                     {

                                               Stringname = fileItem.getFieldName();

                                               Stringvalue = fileItem.getString();

                                               System.out.println(name+ " = " + value);

                                     }

                                     else   // 如果是檔案

                                     {

                                               Stringvalue = fileItem.getName();

                                               intstart = value.lastIndexOf("\\");

                                               StringfileName = value.substring(start + 1);

                                               // 將其中包含的內容寫到path(即upload目錄)下,

                                               // 名為fileName的檔案中

                                               fileItem.write(newFile(path, fileName));

                                     }

                            }

                   }

                   catch(Exception e)

                   {

                            e.printStackTrace();

                   }

                   // 向客戶端反饋結果

                   PrintWriter out =resp.getWriter();

                   out.print("OK");

                   out.flush();

                   out.close();

                   super.doPost(req, resp);

         }

}

再在classes目錄建立如下目錄結構com\pat\handlinghttprequestservlet,這用來代表HandlingHttpRequestServlet這個servlet所在的包名,將編譯好的HandlingHttpRequestServlet.class,拷貝到這個目錄下,然後啟動(或者重新啟動)tomcat

3.       Java application的程式碼

package com.pat.postrequestemulator;

importjava.io.BufferedReader;

importjava.io.DataInputStream;

importjava.io.File;

import java.io.FileInputStream;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjava.io.OutputStream;

importjava.io.Serializable;

importjava.net.HttpURLConnection;

importjava.net.URL;

importjava.util.ArrayList;

public classPostRequestEmulator

{

         public static void main(String[] args)throws Exception

         {

                   // 設定服務地址

                   String serverUrl ="http://127.0.0.1:8080/test/upload";

                   // 設定要上傳的普通Form Field及其對應的value

                   // 類FormFieldKeyValuePair的定義見後面的程式碼

                   ArrayList<FormFieldKeyValuePair> ffkvp = new ArrayList<FormFieldKeyValuePair>();

                   ffkvp.add(newFormFieldKeyValuePair("username", "Patrick"));

                   ffkvp.add(newFormFieldKeyValuePair("password", "HELLOPATRICK"));

                   ffkvp.add(newFormFieldKeyValuePair("hobby", "Computer programming"));

                   // 設定要上傳的檔案。UploadFileItem見後面的程式碼

                   ArrayList<UploadFileItem> ufi = new ArrayList<UploadFileItem>();

                   ufi.add(newUploadFileItem("upload1", "E:\\Asturias.mp3"));

                   ufi.add(newUploadFileItem("upload2", "E:\\full.jpg"));

                   ufi.add(newUploadFileItem("upload3", "E:\\dyz.txt"));

                   // 類HttpPostEmulator的定義,見後面的程式碼

                   HttpPostEmulator hpe = new HttpPostEmulator();

                   String response =hpe.sendHttpPostRequest(serverUrl, ffkvp, ufi);

                   System.out.println("Responsefrom server is: " + response);

         }

}

classHttpPostEmulator

{

         //每個post引數之間的分隔。隨意設定,只要不會和其他的字串重複即可。

         private static final String BOUNDARY ="----------HV2ymHFg03ehbqgZCaKO6jyH";

         public StringsendHttpPostRequest(String serverUrl,

                                                ArrayList<FormFieldKeyValuePair>generalFormFields,

                                                ArrayList<UploadFileItem>filesToBeUploaded) throws Exception

         {

                   // 向伺服器傳送post請求

                   URL url = newURL(serverUrl/*"http://127.0.0.1:8080/test/upload"*/);

                   HttpURLConnection connection= (HttpURLConnection) url.openConnection();

                   // 傳送POST請求必須設定如下兩行

                   connection.setDoOutput(true);

                   connection.setDoInput(true);

                   connection.setUseCaches(false);

                   connection.setRequestMethod("POST");

                   connection.setRequestProperty("Connection","Keep-Alive");

                   connection.setRequestProperty("Charset","UTF-8");

                   connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);

                   // 頭

                   String boundary = BOUNDARY;

                   // 傳輸內容

                   StringBuffer contentBody =new StringBuffer("--" + BOUNDARY);

                   // 尾

                   String endBoundary ="\r\n--" + boundary + "--\r\n";

                   OutputStream out =connection.getOutputStream();

                   // 1. 處理普通表單域(即形如key = value對)的POST請求

                   for(FormFieldKeyValuePairffkvp : generalFormFields)

                   {

                            contentBody.append("\r\n")

                           .append("Content-Disposition: form-data; name=\"")

                           .append(ffkvp.getKey() + "\"")

                           .append("\r\n")

                           .append("\r\n")

                           .append(ffkvp.getValue())

                           .append("\r\n")

                           .append("--")

                           .append(boundary);

                   }

                   String boundaryMessage1 =contentBody.toString();

                   out.write(boundaryMessage1.getBytes("utf-8"));

                   // 2. 處理檔案上傳

                   for(UploadFileItem ufi :filesToBeUploaded)

                   {

                            contentBody = newStringBuffer();

                            contentBody.append("\r\n")

                          .append("Content-Disposition:form-data; name=\"")

                          .append(ufi.getFormFieldName() +"\"; ")   // form中field的名稱

                          .append("filename=\"")

                          .append(ufi.getFileName() +"\"")   //上傳檔案的檔名,包括目錄

                          .append("\r\n")

                          .append("Content-Type:application/octet-stream")

                          .append("\r\n\r\n");

                            StringboundaryMessage2 = contentBody.toString();

                            out.write(boundaryMessage2.getBytes("utf-8"));

                            // 開始真正向伺服器寫檔案

                            File file = newFile(ufi.getFileName());

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

                            int bytes = 0;

                            byte[] bufferOut =new byte[(int) file.length()];

                            bytes =dis.read(bufferOut);

                            out.write(bufferOut,0, bytes);

                            dis.close();

                            contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH");

                            StringboundaryMessage = contentBody.toString();

                            out.write(boundaryMessage.getBytes("utf-8"));

                            //System.out.println(boundaryMessage);

                   }

                   out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n".getBytes("UTF-8"));

                   // 3. 寫結尾

                   out.write(endBoundary.getBytes("utf-8"));

                   out.flush();

                   out.close();

                   // 4. 從伺服器獲得回答的內容

                   String strLine="";

                   String strResponse ="";

                   InputStream in =connection.getInputStream();

                   BufferedReader reader = newBufferedReader(new InputStreamReader(in));

                   while((strLine =reader.readLine()) != null)

                   {

                            strResponse +=strLine +"\n";

                   }

                   //System.out.print(strResponse);

                   return strResponse;

         }

}

// 一個POJO。用於處理普通表單域形如key = value對的資料

classFormFieldKeyValuePair implements Serializable

{

         private static final longserialVersionUID = 1L;

         // The form field used for receivinguser's input,

         // such as "username" in "<inputtype="text" name="username"/>"

         private String key;

         // The value entered by user in thecorresponding form field,

         // such as "Patrick" the abovementioned formfield "username"

         private String value;

         public FormFieldKeyValuePair(Stringkey, String value)

         {

                   this.key = key;

                   this.value = value;

         }

         public String getKey()

         {

                   return key;

         }

         public void setKey(String key)

         {

                   this.key = key;

         }

         public String getValue()

         {

                   return value;

         }

         public void setValue(String value)

         {

                   this.value = value;

         }

}

// 一個POJO。用於儲存上傳檔案的相關資訊

classUploadFileItem implements Serializable

{

         private static final longserialVersionUID = 1L;

         // The form field name in a form used foruploading a file,

         // such as "upload1" in "<inputtype="file" name="upload1"/>"

         private String formFieldName;

         // File name to be uploaded, thefileName contains path,

         // such as "E:\\some_file.jpg"

         private String fileName;

         public UploadFileItem(StringformFieldName, String fileName)

         {

                   this.formFieldName =formFieldName;

                   this.fileName = fileName;

         }

         public String getFormFieldName()

         {

                   return formFieldName;

         }

         public void setFormFieldName(StringformFieldName)

         {

                   this.formFieldName =formFieldName;

         }

         public String getFileName()

         {

                   return fileName;

         }

         public void setFileName(StringfileName)

         {

                   this.fileName = fileName;

         }

}

4.       執行結果

執行PostRequestEmulator之前,伺服器的upload目錄下的情況:

 

執行PostRequestEmulator後,伺服器的upload目錄下的情況:

 

PostRequestEmulator從服務端得到的反饋情況:

Response fromserver is: OK

Tomcat控制檯輸出:

 

如果上傳的檔案中有大於1M的情況,第二次執行PostRequestEmulator的時候,就會在temp目錄中產生臨時檔案。

本文參考材料:

文章2

 在最初的 http 協議中,沒有上傳檔案方面的功能。RFC1867("Form-based File Upload in HTML".)
 http 協議添加了這個功能。客戶端的瀏覽器,如 Microsoft IE, Mozila, Opera 等,按照此規範將用
戶指定的檔案傳送到伺服器。伺服器端的網頁程式,如
 php, asp, jsp 等,可以按照此規範,解析出使用者
傳送來的檔案。

2.1客戶端

簡單來說,RFC1867規範要求http協議增加了file型別的input標籤,用於瀏覽需要上傳的檔案。同時
要求
FORM表單的enctype屬性設定為“multipart/form-data”,method屬性設定為“post”即可,下面是我們文
件上傳頁面的表單程式碼:

<formaction="<%=request.getContextPath()%>/servlet/SimpleUpload"enctype="multipart/form-data"
method
="post">

文字1<inputtype="text"name="text1"value="文字1"><br>

檔案2<inputtype="text"name="text2"value="文字2"><br>

檔案1<inputtype="file"name="file1"><br>

檔案2<inputtype="file"name="file2"><br>

檔案2<inputtype="file"name="file3"><br>

<inputtype="submit"value="開始上傳">

</form>

2.2 伺服器端

一個檔案上傳請求的訊息實體由一系列根據 RFC1867"Form-based File Upload in HTML".)編碼的專案
(文字引數和檔案引數)組成。自己程式設計來解析獲取這些資料是非常麻煩的,還需要了解
RFC1867規範對請
求資料編碼的相關知識。
FileUpload 可以幫助我們解析這樣的請求,將每一個專案封裝成一個實現了FileItem
介面的物件,並以列表的形式返回。所以,我們只需要瞭解FileUploadAPI如何使用即可,不用管它們的底
層實現。讓我們來看一個簡單檔案上傳處理程式碼:

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload uploader = new ServletFileUpload(factory);

List<FileItem> list = uploader.parseRequest(request);

if (item.isFormField()){

// 處理普通表單域

String field = item.getFieldName();//表單域名

String value = item.getString("GBK");

相關推薦

java模擬post傳輸檔案tomcat伺服器servlet接收

網路上一篇介紹這個的文章,如下文章1其實是有問題的。實際上它的模擬http請求的格式有點問題,如果傳輸.txt檔案就會發現.txt檔案裡面多出了一些字元,而這些字元是我們的傳輸檔案頭內容。為什麼會這樣的? 參考文章2我們對比發現文章1的傳輸檔案頭和檔案內容的組合格式有問

利用socket技術實現用java實現客戶向服務傳送檔案伺服器接收檔案並給出一個響應。

通訊是網路程式設計中重要的組成部分,而socket程式設計是網路程式設計的基礎。利用socket可以實現客戶端和伺服器端的通訊。下面我先把客戶端和伺服器端的程式碼粘上去再進行詳細的分析。 package test1; import java.io.File; import java.io

Java 模擬 UDP 傳輸的傳送接收

一、建立 UDP 傳輸的傳送端 建立 UDP 的 Socket 服務; 將要傳送的資料封裝到資料包中; 通過 UDP 的 Socket 服務將資料包傳送出去; 關閉 Socket 服務。 import java.io.IOException; impor

java的簡單入門,tomcat伺服器

Tomcat是一款開源的處理動態非常牛逼的web伺服器。是sun公司開發的,在喪屍危機之後被收購了。 安裝Tomcat需要的支援安裝包 JDK下載:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-21331

收發檔案伺服器/客戶實現

程式需求 客戶端接受使用者輸入的傳輸檔名 客戶端請求伺服器端傳輸該檔名所指檔案 伺服器端程式碼: #include <iostream> #include <string> #include <stdlib.h> #include

Java Web入門(2) 配置tomcat伺服器

Java Web 入門配置tomcat伺服器 (1)在IDEA配置tomcat伺服器 1.下載tomcat9, Mac tar.gz Windows zip 2.Edit configurations-> + ->Tomcat Server ->

騰訊雲部署jsp打包war檔案tomcat伺服器mysql資料庫

首先購買騰訊雲伺服器 配置伺服器的系統為:windows server 2012 R2 中文版 1.初始化密碼 騰訊雲控制檯找到伺服器 更多-密碼/金鑰-重置密碼 2.開放安全組 放通全部安全組 一間放通勾上放通全部 3.遠端連線伺服器 win+r輸入mstsc開啟遠端桌面 找到騰訊雲伺服器

Java Web(二)—— Tomcat伺服器使用技巧

一、搭建JavaWeb應用開發環境——Tomcat伺服器 1.1、WEB伺服器的作用   在本地計算機上隨便建立一個web頁面,使用者是無法訪問到的,但是如果啟動tomcat伺服器,把web頁面放在tomcat伺服器中,使用者就可以訪問了。  1、不管什麼web資源,想被遠端計算機訪問,都必須有

java模擬post請求

HttpURLConnection模擬POST請求 public class HttpUtilTest { public String sendPost(String url, String Params) throws IOException {

JAVA模擬post方式提交URL引數和body內json引數

package test.itsm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStre

通過Postman模擬Json資料並且在伺服器顯示的方法

1. 2. 而在服務端直接新建一個controller: @RestController @RequestMapping("/device") public class DatasPController { @RequestMapping(value = "/

java-基本的Socket程式設計-實現伺服器和客戶通訊

基本的Socket程式設計: 本例項介紹Socket程式設計的基本步驟。啟動Socket服務後,再開啟Socket刻畫段,在輸入框中輸入訊息,然後傳送給伺服器端,伺服器端將收到的訊息返回到客戶端。 關鍵技術: Socket程式設計的關鍵技術如下; —–S

Android手機客戶通過JSP實現與Tomcat伺服器通訊(Msql資料庫,Json作為載體)--服務程式碼

伺服器端主要程式碼: 1.首先構建一個Person類,用來儲存使用者資訊 public class Person private String name; private String address; private Integer age; public P

關於java 傳送http json資料格式請求時,伺服器如何接收json資料並解析

一般情況下,傳送http請求時content-tye是application/x-www-form-urlencoded格式,而這樣的格式會以鍵值對的形似被封裝,至於是在瀏覽器傳送的時候被封裝的還是在伺服器端被封裝的我還不太清楚。但是我的猜測是在瀏覽器傳送請求的時候在客戶端

從服務傳輸檔案到客戶(一對一)

public class FTPServer { //伺服器 public void start(File target) throws IOException{ //建立一個伺服器 ServerSocket ss = new ServerSocket(5678)

java web專案部署到tomcat伺服器(一般步驟和自己所犯錯誤的總結)————高手忽略

最近由於專案需求,需要將java web專案部署到本地tomcat上(版本為8.0)進行測試。作為一個非計算機專業的菜鳥,之前的工作都是寫後臺邏輯程式碼,沒接觸過web專案部署。部署的時候不知道如何下手,參考了其他部落格以及他人問題的解決方法,終於把專案簡單部署到tomca

java學習筆記---qq專案---在伺服器建立的一個Socket陣列來儲存已建立連線套接字

/*  * 首先,在這個實驗中,我想要用我自己的方法,來實現一對一通訊。  *   * 我想採用: 在伺服器端建立一個數組,用於儲存Socket  * 這樣伺服器端每建立一個socket,就儲存一個,同時,每個客戶端都有一個編號,  * 那麼,客戶端的編號也就是伺服器返回給

java模擬post方式提交表單實現圖片上傳

模擬表單html如下: <form action="up_result.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">       <label>

TCP程式設計例三:從客戶傳送檔案伺服器伺服器儲存到本地,並返回“傳送成功”給客戶

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.i

WebApi Post引數物件,伺服器引數物件為空的問題

最近在研究WebApi,在實際的工作中遇到了一個問題:在將引數物件MSG2的例項通過Post至伺服器端的時候, public static string SetMessageOperationResult(MSG2 model) {