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请求
最新推荐文章于 2024-03-13 10:16:05 发布