Home > Web Front-end > HTML Tutorial > How to upload files with HTTPclient using MultipartEntity_html/css_WEB-ITnose

How to upload files with HTTPclient using MultipartEntity_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 12:01:08
Original
1364 people have browsed it

jsp HTTPclient MultipartEntity multipart/form-data

jsp page upload file code:





httpclient I don’t know how to write it,
I checked it online Most of them are copied by you and me and I copy you.
This is how it is written on the Internet
The jsp code is as follows
enctype="multipart/form-data">



"/>


The acquired code is written like this

MultipartEntity entity = new MultipartEntity();
entity.addPart("param1", new StringBody("China", Charset.forName("UTF-8")));
entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8"))) ;
entity.addPart("param3", new FileBody( new File("C:\1.txt")));

HttpPost request = new HttpPost(“http://localhost/index .html”);
request.setEntity(entity);

I don’t understand. The above paths are all selected for file upload, and they write code using
entity.addPart(" param3", new FileBody( new File("C:\1.txt")));
The file paths are all hard-coded. It seems that there is no new File() for file upload! Because the code is on the server side, how could it be written like this?
The local code uploaded by the user is a local path. The server side definitely does not have this address.

I don’t even know the above code and they just write it without verifying it themselves

Please help me, experts, how to solve this problem.
The server-side interface requires the data multipart/form-data. How should I write it?



Reply to the discussion (solution)

You first understand what HTTPclient is used for
The function of HTTPclient is to simulate a browser in jsp, that is, HTTP protocol Client (client)
Your background code is to upload files on your local server to the target server like a browser
So new File("C:\1.txt" ) problem can be solved, right? C:\1.txt is a file in your local server. Of course, the file name is determined by you

As for the multipart/form-data statement, it is automatically added by the parameter MultipartEntity of HttpPost

What I want is to upload web pages to the server. The server uses HTTPclient to call another service interface to upload, instead of uploading my local files

Because this interface stipulates that only multipart/form-data can be transmitted to the browser. The uploaded file information will be obtained through the background here and then transferred to the interface to perform the save. The interface will store the respective data of the operation, etc.

My page is like this. This window has an upload function. Submit it and submit it to the background. The background then uses httpclient to redirect to another interface server. You need to transfer the data there. The interface requires multipart/form- data This file stream, I don’t know how to use httpclient to transfer it now, because I haven’t used HTTPclient before

Upload function window

Upload the data requested to the background


This is the data passed to the background. Now I want httpclient to get multipart/form-data, but I don’t know how to do it

Request URL: http://localhost:8080/proxy/api/images/attachments/ json/0/67/0/0/-1?Type=Image&CKEditor=textEditor&CKEditorFuncNum=1&langCode=zh-cn
Request Headers CAUTION: Provisional headers are shown.
Accept: text/html,application/xhtml xml, application/xml;q=0.9,image/webp,*/*;q=0.8
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarysw8ttG9a1gakIbQt
Origin:http://localhost: 8080
Referer:http://localhost:8080/user/kouht/editonline
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36
Query String Parametersview sourceview URL encoded
Type:Image
CKEditor:textEditor
CKEditorFuncNum:1
langCode:zh-cn
Request Payload
---- --WebKitFormBoundarysw8ttG9a1gakIbQt
Content-Disposition: form-data; name="upload"; filename="menu.png"
Content-Type: image/png


---- --WebKitFormBoundarysw8ttG9a1gakIbQt--

The file uploaded by your browser is uploaded to your own server. After receiving it, you only need to use HTTPclient when transmitting it to other servers.
This is a relay, don't get confused!

The file uploaded by your browser is uploaded to your own server. After receiving it, you only need to use HTTPclient when sending it to other servers.
This is a relay, don’t get confused!



Can’t it be transferred directly to another server?

No!
Because jsp starts to work when the browser finishes uploading files
And HTTPclient only simulates the browser and uploads files in file mode
If you want to receive the data of the uploaded file in jsp while sending it to the superior If the server sends it
firstly, you have to write the file receiving program yourself, and secondly, you have to use socket to send it to the upper-level server
There is too much knowledge involved, and you will not be able to do it for a while

No!
Because jsp starts to work when the browser finishes uploading files
And HTTPclient only simulates the browser and uploads files in file mode
If you want to receive the data of the uploaded file in jsp while sending it to the superior If the server sends it
firstly, you have to write the file receiving program yourself, and secondly, you have to use socket to send it to the superior server
There is too much knowledge involved, and you may not be able to do it for a while



It seems to be possible. I looked at their previous code and it is possible. It doesn’t need to be so troublesome. This is what they wrote

The following method is the path I mentioned above. Request URL:http://localhost:8080/proxy/api/images/attachments/json/0/67/0/0/-1?Type=Image&CKEditor=textEditor&CKEditorFuncNum=1&langCode=zh-cn
protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String targerUrl =request.getRequestURI();
HttpProxy.request(request, response, targerUrl); // Proxy request
}

/**
* Proxy request
*
* @param request
* - Request
* @param response
* - Response
* @param targetUrl
* - Target Server Address
* @param encoding
* - Encoding format of the target server
* @return
* @throws IOException
*/
public static void request(HttpServletRequest request, HttpServletResponse response, String targetUrl) throws IOException {

// System.out.println("Enter Http proxy");

// Target url
if (null == targetUrl) {
throw new IOException("Missing target server address");
}

// Target server Address
String url = null;

// Get the target server address and re-encode the Chinese in the target server
try {
url = ProxyUtils.rebuildURL2(targetUrl, "utf -8");
} catch (Exception e) {
e.printStackTrace();
}

// Request parameters
Map params = new HashMap();

// Request header information
Map headers = new HashMap();

// Client request method
String method = request.getMethod();

logger.info("[proxy request] method: " " method ": " url);

// Get Enumeration of request header information
Enumeration headersEnu = request.getHeaderNames();
while (headersEnu.hasMoreElements()) {
// Get the request header name
String headerName = (String) headersEnu.nextElement();
String headerValue = request.getHeader(headerName);
headers.put(headerName.toLowerCase(), headerValue);
logger.info("t[header] " headerName " "=" headerValue);
}

// If there is a specified request header, overwrite the original request header
if (null != headerMap && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
headers.put(key.toLowerCase(), headerMap.get(key));
}
}
// Get the parameter key name
Enumeration enu = request.getParameterNames();
while (enu.hasMoreElements()) {
// Get the parameter name list
String paramName = ( String) enu.nextElement();
// Process the parameters of this request and the parameters sent to the third-party server
String paramValue = request.getParameter(paramName);
params.put(paramName, paramValue);
logger.info("t[parameter] " paramName "=" paramValue);
}

// Get ajax proxy
AjaxProxy proxy = ProxyFactory.getProxyInstance(method, url, params , headers);

// // Request body
// String requestBody = readFileByLines(request.getInputStream());
//
// System.out.println(" n[requestBody]" requestBody);

// Get ajax proxy response
AjaxResponse resp = null;

// If it is a post request and it is a form upload (multipart/form-data), pass the input stream
String contentType = headers.get("content-type");
boolean isUpload = null != contentType && contentType.toLowerCase().indexOf("multipart/form-data") >= 0;

// 1. When the requested resource is an image, directly use the stream as the response to return the result
String accept = headers.get("accept");
boolean useStream4response = null != accept ? (accept.indexOf("image/") >= 0) : true;

// Always use Stream as return value
useStream4response = true;

if ("post".equalsIgnoreCase(method) && isUpload) {
useStream4response = false;
// Expect to return xml format after uploading the image Data
headers.put("accept", "application/json");
resp = proxy.getAjaxResponse(request.getInputStream());
// } else if ( "put".equalsIgnoreCase( method) && params.size() > 0 )
// {
// // put request, with parameters, pass input stream
// resp = proxy.getAjaxResponse(request.getInputStream( ));
} else if (useStream4response) {
OutputStream out = response.getOutputStream();
resp = proxy.getAjaxResponse(out);
out.flush();
} else {
resp = proxy.getAjaxResponse();
}

// Get method
HttpMessage httpMethod = resp.getMethod();

// When there is no response httpMethod is null
if (null == httpMethod) {
logger.info("[Proxy request failed] http code: " resp.getStatusCode() ": " url);
return;
}

// Get response headers
Header[] respHheaders = httpMethod.getAllHeaders();
for (int i = 0, len = respHheaders.length; i < len; i ) {
Header header = respHheaders[i];
if (!isOverrideCookie && "Set-Cookie".equalsIgnoreCase(header.getName())) {
continue;
}
if ( "content-type".equalsIgnoreCase(header.getName())) {
if ("post".equalsIgnoreCase(method) && isUpload) {
// If uploading, contentType will not be overwritten
response. setCharacterEncoding("utf-8");
continue;
}
}
response.setHeader(header.getName(), header.getValue());
logger.info(" t[response header] " header.getName() "=" header.getValue());
}

// Output
if (useStream4response) {
logger.info(" Request address: " url "n-----Return result: [Stream]");
} else {
PrintWriter out = response.getWriter();
String result = resp.getContent() ;
out.print(result);
}
return;
}

Use this red code to upload it

You follow what he wrote Was it successful?

His idea is completely different. He wrote a proxy server
Use your server to make client requests

It should be noted that when writing a proxy server, do not Peep into user data. This is against professional ethics

Yes, this is successful. There is no peeking. This is equivalent to getting all the information requested by the browser and then using the proxy to request it again, leaving the data intact. Please request again

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template