我是靠谱客的博主 阔达水池,这篇文章主要介绍最原始的http请求,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
private String request3(String requestMessage,String txUrl) throws Exception{ log.info(txUrl); URL url = new URL(txUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true); connection.setDoOutput(true); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8")); PrintWriter pw = new PrintWriter(bw, true); // 发起请求 pw.println(requestMessage); log.info("请求xml:"+requestMessage); log.info("响应代码:"+connection.getResponseCode()); if(200 == (connection.getResponseCode())){ InputStream is = connection.getInputStream(); String result = inputStreamToString(is); pw.close(); bw.close(); log.info("请求成功:"+result.toString()); return result.toString(); }else{ InputStream is = connection.getErrorStream(); //通过getErrorStream了解错误的详情,因为错误详情也以XML格式返回,因此也可以用JDOM来获取。 String result = inputStreamToString(is); pw.close(); bw.close(); throw new Exception("响应代码" + connection.getResponseMessage() + "。错误原因是:" + result); } } /** * 读取数据 * @param is * @return * @throws Exception */ private String inputStreamToString(InputStream is) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8")); String temp = null; StringBuffer result = new StringBuffer(); while ((temp = br.readLine()) != null) { result.append(temp); } br.close(); is.close(); return result.toString(); }

最后

以上就是阔达水池最近收集整理的关于最原始的http请求的全部内容,更多相关最原始内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部