HttpURLConnection 发送PUT请求 json请求体 与服务端接收

发送请求:

public void testHttp()
    {
        
        String result = "";
        try
        {
            URL postURL = new URL("http://localhost:8080/webTest/TestSerlvte");
            HttpURLConnection conn = (HttpURLConnection) postURL.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
//            conn.setConnectTimeout(5 * 1000);  
            // PUT请求
            conn.setRequestMethod("PUT");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // json格式上传的模式
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("header1", "header1Text1");
            conn.setRequestProperty("header2", "header1Text2");

            String payload = "{\"appid\":6,\"appkey\":\"0cf0vGD/ClIrVmvVT/r5hEutH5M=\",\"openid\":200}";

//            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
            //解决中文乱码
            PrintWriter osw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            osw.write(payload);
            osw.flush();
            osw.close();
            System.out.println(conn.getResponseCode());
            if (conn.getResponseCode() == 200) {  
                InputStreamReader isr = new InputStreamReader(conn.getInputStream());  
                BufferedReader br = new BufferedReader(isr);  
                String inputLine = null;  
                while ((inputLine = br.readLine()) != null) {  
                    result += inputLine;  
                }  
                isr.close();  
                conn.disconnect();  
            } 
            else {
                //如果出错,一定要检查URL对没有!
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
                String jsontxt = br.readLine();
                br.close();
            }

            conn.disconnect();
            
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }

    }

  

 

服务端:

@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("我是PUT");
		req.getHeader("header4");
		System.out.println("header4" + "----" + req.getHeader("header4"));
		
		ServletInputStream inputStream = req.getInputStream();
		
	    StringBuilder content = new StringBuilder();  
	    byte[] b = new byte[req.getContentLength()];  
	    int lens = -1;  
	    while ((lens = inputStream.read(b)) > 0) {  
	        content.append(new String(b, 0, lens));  
	    }  
	    String strcont = content.toString();// 内容     
		
		resp.setHeader("resp1", "resp1Text");
		super.doPut(req, resp);
	}

  

posted @ 2017-07-19 18:14  MokeyChan  阅读(1546)  评论(0编辑  收藏  举报