java测试httprequest(为手游开发后台数据传输做准备)

1.测试类

package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class httprequestTest
{
  public static Log log = LogFactory.getLog(httprequestTest.class);

  public static String sendGet(String url, String param)
  {
    String result = "";
    BufferedReader in = null;
    try {
      String urlNameString = url + "?" + param;
      URL realUrl = new URL(urlNameString);

      URLConnection connection = realUrl.openConnection();

      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection", "Keep-Alive");
      connection.setRequestProperty("user-agent", 
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

      connection.connect();

      Map map = connection.getHeaderFields();

      in = new BufferedReader(
        new InputStreamReader(connection.getInputStream()));
      String line;
      while ((line = in.readLine()) != null)
      {
        if (result.isEmpty())
          result = result + line;
        else
          result = result + "\n" + line;
      }
    }
    catch (Exception e) {
      log.error("发送GET请求出现异常!" + e);
      log.error(e, e.fillInStackTrace());
    }
    finally
    {
      try {
        if (in != null)
          in.close();
      }
      catch (Exception ex) {
        log.error(ex, ex.fillInStackTrace());
      }
    }
    return result;
  }

  public static String sendPost(String url, String param)
  {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
      URL realUrl = new URL(url);

      URLConnection conn = realUrl.openConnection();

      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent", 
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

      conn.setDoOutput(true);
      conn.setDoInput(true);

      out = new PrintWriter(conn.getOutputStream());
      out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));

      out.print(param);

      out.flush();

      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null)
      {
        if (result.isEmpty())
          result = result + line;
        else
          result = result + "\n" + line;
      }
    }
    catch (Exception e) {
      log.error("发送 POST 请求出现异常!" + e);
      log.error(e, e.fillInStackTrace());
    }
    finally
    {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null)
          in.close();
      }
      catch (IOException ex) {
        log.error(ex, ex.fillInStackTrace());
      }
    }
    return result;
  }

  public static void main(String[] args) throws Exception
  {
    String url = "http://localhost:8080/shxx/myhttprequest.test";
    String string= sendPost(url, "a=33");
    System.out.println(string);
  }
}
2.简单的servlet
package com.zz;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;


public class MyServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("收到get请求");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("text/html");
		OutputStreamWriter out=null;
		File file=new File("D:\\work\\android\\周垚.doc");
		FileInputStream input=null;
		try {
//			input=new FileInputStream(file);
//			String filename=URLEncoder.encode(file.getName());
//			response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
//			out=response.getOutputStream();
//			byte[] bytes=new byte[1024];
//			int len=-1;
//			while ((len=input.read(bytes))!=-1) {
//				out.write(bytes);;
//			}
			out=new OutputStreamWriter(response.getOutputStream());
			out.write("aaaaa");
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(input!=null){
				input.close();
			}
			if(out!=null){
				out.close();
			}
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("收到post请求");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("text/html");
		OutputStreamWriter out=null;
		File file=new File("D:\\work\\android\\周垚.doc");
		FileInputStream input=null;
		try {
//			input=new FileInputStream(file);
//			String filename=URLEncoder.encode(file.getName());
//			response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
//			out=response.getOutputStream();
//			byte[] bytes=new byte[1024];
//			int len=-1;
//			while ((len=input.read(bytes))!=-1) {
//				out.write(bytes);;
//			}
			out=new OutputStreamWriter(response.getOutputStream());
			out.write("aaaaa");
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(input!=null){
				input.close();
			}
			if(out!=null){
				out.close();
			}
		}
	}
	public static void main(String[] args) throws Base64DecodingException {
		File file=new File("D:\\work\\android\\周垚.doc");
		String filename=file.getName();
		filename=URLDecoder.decode(filename);
		filename=URLEncoder.encode(filename);
		
		String filename1=Base64.encode(filename.getBytes());
		System.out.println(filename1);
		filename1=new String(Base64.decode(filename1));
		System.out.println(filename1);
		System.out.println(URLDecoder.decode(filename1));
		System.out.println(System.getProperty("file.separator"));
	}
	
}

3.web.xml配置

<servlet>
		<servlet-name>mytest</servlet-name>
		<servlet-class>com.zz.MyServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>mytest</servlet-name>
		<url-pattern>*.test</url-pattern>
	</servlet-mapping>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值