首页 > 代码库 > HttpURLConnection 发送PUT请求 json请求体 与服务端接收
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()); 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); }
HttpURLConnection 发送PUT请求 json请求体 与服务端接收
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。