欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java http方式调用接口 方法共享

程序员文章站 2022-05-23 21:00:54
...

java  调用别人接口,http 调用参数 

url:对方的http访问链接;

json: 对方指定的json 格式字符串;

 

 

    public static void main(String[] args) {
        Class class = new Class();
        String url="http://127.0.0.1/admin/insertInto";
        String json="{\"city_name\":\"上海\",\"hire_way\":2,\"house_title\":\"绿地新江桥城(西区)2室-1厅-1卫合租\",\"month_rent\":1200,\"data_status\":0}\n";
        String result = class.HttpStringPostRequest(url,json);
        System.out.println("result:"+result);

    }

 

 /**
     * HttpClient发送json字符串post请求
     * @param
     * @param json
     * @return
     */
    public String HttpStringPostRequest(String url, String json) {

        System.out.println("HttpStringPostRequest - result - url:" + url);
        System.out.println("HttpStringPostRequest - result - json:" + json);
        String returnValue = "这是默认返回值,接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步:创建HttpClient对象
            httpClient = HttpClients.createDefault();

            //第二步:创建httpPost对象
            HttpPost httpPost = new HttpPost(url);

            //第三步:给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");

            httpPost.setHeader("Content-type", "application/json");

            httpPost.setEntity(requestEntity);

            //第四步:发送HttpPost请求,获取返回值
            returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时,必须用此方法


        }
        catch(Exception e)
        {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //第五步:处理返回值
        return returnValue;
    }

 

 

 

温馨提示:

 

返回错误的时候,可以尝试更改一下 header的Content-type 类型:

  httpPost.setHeader("Content-type", "application/json");

 

 我的json是单条数据,json数组是也可以同样适用,用list对象转成二维数组json就可以了 ;