java http请求的服务端和客户端

java基于URLConnection进行http请求:

servlet服务端例子:

         接收请求的方式1:      

         这种方式数据量大的话可能有问题,具体原因还为查清。

 
 
     OutputStream opt = response.getOutputStream();
     String name = request.getParameter("name");
     String age = request.getParameter("age");
     System.out.println("========"+name+"=="+age);
     opt.write((name+"=="+age).getBytes("GBK")); //给调用方响应数据
     opt.flush();
     opt.close();
     ---------------------------------------------------------------------------------------
    接收请求的方式2: 流的方式        
    int leng = 0;
    byte[] buf = new byte[1024];
    ByteArrayOutputStream out1 = new ByteArrayOutputStream();
    OutputStream opt = response.getOutputStream();    

    InputStream in = request.getInputStream();
    while ((leng = in.read(buf))!=-1) {
	out1.write(buf, 0, leng);
	out1.flush();
    }
    in.close();
    System.out.println(new String(out1.toByteArray()));

    opt.write((name+"=="+age).getBytes("GBK")); //给调用方响应数据

 
 

客户端:


         

public class Demo {
	public static void main(String[] args) {
		URL url = null;
        HttpURLConnection conn = null;
        BufferedReader readInfo = null;
        StringBuffer returnXml =new StringBuffer();
        OutputStream out = null;
        try {
            url = new URL("http://10.100.16.236:8080/lftest/servlet/SendXml");
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(1200);
            conn.setReadTimeout(1200);
            //conn.setRequestProperty("content-type", "text/plain");
            conn.setRequestMethod("POST");
            conn.setUseCaches(false); // 忽略缓存
            conn.setDoOutput(true); // 使用 URL 连接进行输入
            conn.setDoInput(true); // 使用 URL 连接进行输入
		    StringBuffer sb = new StringBuffer();
		    out = conn.getOutputStream();
		    String age = "ffsdfdsfdsfdsf";
		    out.write(("name=123&age="+age+"").getBytes("GBK"));
            out.flush();
            out.close();
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {// 正确返回
                readInfo = new BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"GBK"));
                String line = null;
                while ((line = readInfo.readLine()) != null) {
                    returnXml.append(line);
                }
                System.out.println(conn.getResponseCode());
                System.out.println(returnXml.toString());
            }
        }catch (Exception e) {
			// TODO: handle exception
        	e.printStackTrace();
		}finally{
			conn.disconnect();
		}
	}
}




猜你喜欢

转载自blog.csdn.net/u010509052/article/details/53219967