`
canofy
  • 浏览: 820834 次
  • 性别: Icon_minigender_1
  • 来自: 北京、四川
社区版块
存档分类
最新评论

获取POST数据的值

    博客分类:
  • j2EE
阅读更多
     当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();
    }
}


分享到:
评论
3 楼 xmh8023 2015-02-09  
2 楼 xmh8023 2015-02-09  
我访问别的服务器怎么办?急求
1 楼 xmh8023 2015-02-09  
String urlString="http://localhost:8080/login"; 
地址只能是本地吗

相关推荐

Global site tag (gtag.js) - Google Analytics