JAVA代码中访问外部接口传递JSON格式参数

/**
  * 访问指定的URL地址
  * urlStr url地址
  * json json格式字符串
  */
public
static String getURLByPost(String urlStr, String json) { StringBuilder sb = new StringBuilder(); String url = urlStr; // 创建连接对象 HttpClient httpClient = new HttpClient(); // 创建请求 PostMethod method = new PostMethod(url); // 设置请求头格式为json格式 RequestEntity entity = null; try { entity = new StringRequestEntity(json, "application/json", "UTF-8"); // 设置请求体信息 if (entity == null) return ""; method.setRequestEntity(entity); // 设置请求头信息 method.setRequestHeader("APPKEY", "C6C6E17AC153ED8DF8D61207"); // 创建连接 httpClient.executeMethod(method); // 获取返回信息 InputStream in = method.getResponseBodyAsStream(); InputStreamReader isr = new InputStreamReader(in, "UTF-8"); char[] b = new char[4096]; for (int n; (n = isr.read(b)) != -1;) { sb.append(new String(b, 0, n)); } } catch (UnsupportedEncodingException e) { System.out.println("=====JSON数据转换有误。参数json数据:" + json + "END====="); e.printStackTrace(); } catch (HttpException e) { System.out.println("=====URL连接失败。url:" + url + "END====="); e.printStackTrace(); } catch (IOException e) { System.out.println("=====参数传递失败。END====="); e.printStackTrace(); } return sb.toString(); }

 

posted @ 2022-08-29 11:42  乡野小猫  阅读(1501)  评论(0编辑  收藏  举报