Java代码:调用外部接口(使用Json格式传递参数)的方法

Java代码:调用外部接口(使用Json格式传递参数)的方法

 

https://blog.csdn.net/guoshijie8023/article/details/81634278

代码如下:

        String url="所给外部接口的url";
        //创建连接对象
        HttpClient httpClient = new HttpClient();
        //创建请求
        PostMethod method = new PostMethod(url);
        //设置请求头格式为json格式
        RequestEntity entity=new StringRequestEntity(json,"application/json","UTF-8");
        //设置请求体信息
        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));
                     }
              String returnStr = sb.toString();
 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个示例Java代码,用于调用一个接口并发送JSON格式的正文: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class ApiClient { public static void main(String[] args) { try { URL url = new URL("http://example.com/api"); // 接口URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 请求方法为POST connection.setRequestProperty("Content-Type", "application/json"); // 设置请求头为JSON格式 connection.setDoOutput(true); // 构造请求正文 String requestBody = "{\"name\": \"John\", \"age\": 30}"; // 发送请求正文 OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestBody); writer.flush(); writer.close(); // 获取响应结果 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出响应结果 System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们首先指定了要调用接口的URL。然后,我们创建一个`HttpURLConnection`对象,并设置请求方法为POST。接下来,我们设置请求头为JSON格式,并打开输出流以便于发送请求正文。我们构造了一个简单的JSON对象作为请求正文,并通过`OutputStreamWriter`将其发送。最后,我们使用`BufferedReader`读取响应结果,并将其作为字符串输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值