HttpURLConnection 发送PUT请求 json请求体 与服务端接收
2021-06-18 18:03
标签:sage tin byte line 接收 har ext1 readline rect 服务端: HttpURLConnection 发送PUT请求 json请求体 与服务端接收 标签:sage tin byte line 接收 har ext1 readline rect 原文地址:http://www.cnblogs.com/endtel/p/7207180.htmlpublic 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);
}
上一篇:JSP和JSP的运行机制
下一篇:js 下载远程图片
文章标题:HttpURLConnection 发送PUT请求 json请求体 与服务端接收
文章链接:http://soscw.com/index.php/essay/95589.html