HttpURLConnection 发送PUT请求 json请求体 与服务端接收
Posted MokeyChan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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请求体 与服务端接收的主要内容,如果未能解决你的问题,请参考以下文章
来自 inputStream 的内容的 HTTP PUT 请求,大小未知,无法在 HttpUrlConnection 中设置 ChunkedStreamingMode