调用接口实例

public class RworgDetailServiceImpl implements RworgDetailService {

  private static volatile CloseableHttpClient httpClient;

  static {

    initHttpClient();

  }

 

  private static HttpClient initHttpClient(){

    if(httpClient == null){

      synchronized(HttpClient.class){

        if(HttpClient == null){

          httpClient = HttpClients.createDefault();

        }

      }

    }

    return httpClient;

  }

  

  public JSONObject getGwUrl(String userid,String versionguId){

    JSONObject result = new JSONObject();

    String src = "ip地址";

    String path = src +"?userid="+userid+"&versionguId="+versionguId;

    HttpPost httpPost = new HttpPost(path);//建立HttpPost对象

    CloseableHttpResponse  httpResponse = null;

    try{

      //建立一个NameValuePair数组,用于存储传送的数据

      List<NameValuePair> params=new ArrayList<NameValuePair>();
      //添加参数
      params.add(new BasicNameValuePair("versionguId",versionguId);
      //设置编码
      httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
      //发送Post,并返回一个HttpResponse对象
      httpResponse=httpClient.execute(httppost);

      int httpCode = httpResponse.getStatusLine().getStatusCode();

      JSONObject searchResult = new JSONObject();

      if(httpCode==200){

        searchResult.put("data",EntityUtils.tostring(httpResponse.getEntity()));

        if(searchResult.get("data") instanceof String){

          String str = searchResult.getString("data");

          JSONArray dataArray = JSONArray.fromObject(str);

          result = (JSONObject) dataArray.get(0);

        }else{

          result = (JSONObject) searchResult.get("data");

        }

      }

    }catch(Exception e){

      e.printStackTrace();

    }finally{

      if(httpResponse !=null){

        httpresponse.close();

      }

    }

    return result;

  }

}

posted @ 2020-05-22 14:35  790021521  阅读(204)  评论(0)    收藏  举报