获取POST数据的值

本文介绍了一种使用multipart/form-data作为Content-Type的POST请求方法,详细解释了如何通过Java代码发送包含文件和其他参数的请求,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当method为POST,Content-Type为multipart/form-data时,一般应用场景是上传文件,当在该form下还有其它的input时,用request.getParameter("name")则获取不到它的值,需要换一种方式来获取input的值。
例子如下:
1、下面这个类是模拟请求的类,发送一个文件,以及其它的一些参数

package com.demo;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class RequestPostTest {

public static void main(String[] args) throws Exception{
//发起post请求
String urlString="http://localhost:8080/login";
String filePath="D:\\company\\voice\\十渡.wav";
URL connectURL = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
conn.setReadTimeout(100000);
conn.setConnectTimeout(100000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type", "multipart/form-data;");
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
StringBuffer sb=new StringBuffer("Content-Disposition: form-data;");
sb.append("&loginName=test&pwd=test1");
dos.writeBytes(sb.toString());

FileInputStream fileInputStream=new FileInputStream(filePath);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];

//read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

dos.flush();
dos.close();

//接收发起请求后由服务端返回的结果
int read;
StringBuffer inputb = new StringBuffer();
InputStream is = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8");
while ((read=inputStreamReader.read())>=0) {
inputb.append( (char) read);
}
System.out.println(inputb.toString());
}
}

2、获取前台发起的post请求,并获取相应的参数(并未实现)

package com.demo;

import java.io.IOException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;

public class Login extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -5376047309978396611L;

public void doGet(HttpServletRequest request,HttpServletResponse response){
this.doPost(request, response);
}

public void doPost(HttpServletRequest request,HttpServletResponse response){
//测试
try {
ServletInputStream in = request.getInputStream();
System.out.println("-------"+readLine(in));//这里是前台发起的所有参数的值,包括二进制形式的文件和其它形式的文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return ;
}


/**
* Read the next line of input.
*
* @return a String containing the next line of input from the stream, or
* null to indicate the end of the stream.
* @exception IOException
* if an input or output exception has occurred.
*/
private String readLine(ServletInputStream in) throws IOException{
byte[] buf = new byte[8 * 1024];
StringBuffer sbuf = new StringBuffer();
int result;
// String line;

do {
result = in.readLine(buf, 0, buf.length); // does +=
if(result != -1) {
sbuf.append(new String(buf, 0, result, "UTF-8"));
}
}
while(result == buf.length); // loop only if the buffer was filled

if(sbuf.length() == 0) {
return null; // nothing read, must be at the end of stream
}

// Cut off the trailing \n or \r\n
// It should always be \r\n but IE5 sometimes does just \n
int len = sbuf.length();
if(sbuf.charAt(len - 2) == '\r') {
sbuf.setLength(len - 2); // cut \r\n
}
else {
sbuf.setLength(len - 1); // cut \n
}
return sbuf.toString();
}
}
在使用POST方法获取数据时,如果获取不到数据,可能有以下几个原因: 1. **请求参数错误**:确保在发送POST请求时,参数名称和参数都正确无误。可以通过浏览器开发者工具或抓包工具(如Fiddler、Wireshark)来检查请求参数。 2. **服务器端处理逻辑错误**:检查服务器端处理POST请求的代码,确保服务器端正确接收并处理了请求参数。可以使用日志记录请求参数和处理过程,方便调试。 3. **跨域问题**:如果前端和后端不在同一个域名下,可能会遇到跨域问题。需要在服务器端设置CORS(跨源资源共享)头部,允许跨域请求。 4. **请求格式问题**:确保请求的Content-Type头部设置正确。例如,如果发送的是JSON数据,Content-Type应该设置为`application/json`。如果发送的是表单数据,Content-Type应该设置为`application/x-www-form-urlencoded`。 5. **服务器端未正确返回数据**:检查服务器端是否正确返回了响应数据,并且响应状态码为200。可以通过浏览器开发者工具或抓包工具来查看服务器的响应。 6. **网络问题**:确保网络连接正常,没有防火墙或代理服务器阻止请求。 7. **前端代码问题**:检查前端代码中发送请求的部分,确保请求正确发送并处理响应数据。 以下是一个使用JavaScript发送POST请求的示例: ```javascript fetch('https://example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key1: 'value1', key2: 'value2' }) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值