Download api json.

@param req    the req
@param method the method
@param url    the url
@param res    the res
518259
@GetMapping("/setting/download/api/json")
    public void downloadApiJson(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) {
        this.validationSessionComponent.sessionCheck(req);
        url = new String(Base64.getDecoder().decode(url));
        List<ValidationData> list = this.msgSettingService.getValidationData(method, url);
        ValidationFileUtil.sendFileToHttpServiceResponse(method + url.replaceAll("/", "-") + ".json", list, res);
    }
962825
protected HttpUriRequest setupRequestJson(final String path, final String method, final String params) {
        final HttpUriRequest request = buildMethod(method, path, params);
        request.addHeader(new BasicHeader("Accept", "application/json"));
        request.addHeader(new BasicHeader("Accept-Charset", "utf-8"));
        request.setHeader(new BasicHeader("Authorization", "Basic " + new String(Base64.encodeBase64((this.token + ":" + this.secret).getBytes()))));
        return request;
    }
383439
public RequestBuilder request(String method, String url) {
        try {
            return request(method, new URL(url));
        } catch (MalformedURLException e) {
            log.error("url exception", e);
            throw new IllegalArgumentException(e);
        }
    }
86921
@GetMapping("/setting/download/api/excel/all")
    public void downloadApiAll(HttpServletRequest req, HttpServletResponse res) {
        this.validationSessionComponent.sessionCheck(req);
        PoiWorkBook workBook = this.msgExcelService.getAllExcels();
        workBook.writeFile("ValidationApis_" + System.currentTimeMillis(), res);
    }
230879
@WebOperationMethod
    public Map<String,Object> download(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String database = Objects.get(params, "database");
        String collection = Objects.get(params, "collection", COLLECTION);
        String id = Objects.get(params, "id");

        FileStorage.FileReadBean b = null;
        try{
            b = FileStorage.read(new Id(database,collection,id));
            response.setContentType(b.getMeta().getContentType());
            try {
                IOUtils.copy(b.getInputStream(), response.getOutputStream());
            } catch (IOException e) {
                throw S1SystemError.wrap(e);
            }
        }catch (NotFoundException e) {
            response.setStatus(404);
        }finally {
            FileStorage.closeAfterRead(b);
        }
        return null;
    }
1251018
public static HttpResponse execute(final String url, final String method) {
        return execute(url, method, null, null, new HashMap<>(), new HashMap<>());
    }
752605
def _request(self, method, resource_uri, **kwargs):
        
        data = kwargs.get('data')
        response = method(self.API_BASE_URL + resource_uri,
                          json=data, headers=self.headers)
        response.raise_for_status()
        return response.json()
228330
def _http_request(url,
                  method='GET',
                  headers=None,
                  data=None):
    '''
    
    '''
    req = requests.request(method,
                           url,
                           headers=headers,
                           data=data)
    ret = _default_ret()
    ok_status = METHOD_OK_STATUS.get(method, 200)
    if req.status_code != ok_status:
        ret.update({
            'comment': req.json().get('error', '')
        })
        return ret
    ret.update({
        'result': True,
        'out': req.json() if method != 'DELETE' else None  # no body when DELETE
    })
    return ret
579385
public static JSONObject getJSONObject(HttpPost request, Integer method, HashMap<String, String> params) throws JSONException {
        switch (method) {
        case METHOD_PUT:
        case METHOD_DELETE:
        case METHOD_POST:
            return doPostRequest(request, params);
        default:
            throw new RuntimeException("Wrong http method requested");
        }
    }
142676
function makerequest(method, url, data, cb) {
    var rq = superagent(method, url);

    rq.set('User-Agent', self.agent);
    rq.set('Accept', self.version + '+json'); // always use json

    if (self.timeout)  { rq.timeout(self.timeout); }
    if (self.username) { rq.auth(self.username, self.password); }
    if (data) { rq.send(data); }

    rq.end(function(err, resp) {
      err = (resp && resp.error) || err;
      debug(method + ' ' + url + ' ' + (err || '') + '(X-RateLimit-Remaining: ' + resp.header['x-ratelimit-remaining'] + ')');
      if (err) return cb(err);
      return cb(null, resp.body);
    });
  }
934169
function download(url) {
  return request('GET', url).then(function (res) {
    var out = {
      url: url,
      body: res.body,
      statusCode: res.statusCode,
      headers: res.headers,
      dependencies: []
    };

    try {
      if (out.statusCode === 302) {
        out.dependencies = [out.headers.location];
      } else if (!out.headers['content-type']) {
        out.dependencies = [];
      } else if (out.headers['content-type'].indexOf('text/html') !== -1) {
        out.dependencies = htmldeps(out.body.toString());
      } else if (out.headers['content-type'].indexOf('text/css') !== -1) {
        out.dependencies = cssdeps(out.body.toString());
      } else {
        out.dependencies = [];
      }
    } catch (ex) {
      ex.message = 'Error parsing deps for "' + url + '": ' + ex.message;
      throw ex;
    }
    return out;
  });
}
873678
def _put_or_post_json(self, method, url, data):
        
        if self.parsed_endpoint.scheme == 'https':
            conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
        else:
            conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)
        head = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": USER_AGENT,
            API_TOKEN_HEADER_NAME: self.api_token,
        }
        if self.api_version in ['0.1', '0.01a']:
            head[API_VERSION_HEADER_NAME] = self.api_version
        conn.request(method, url, json.dumps(data), head)
        resp = conn.getresponse()
        self._handle_response_errors(method, url, resp)
        return json.loads(resp.read())
459511
function(method, params, payload) {
        var baseUrl   = (method.base_url || this.spec.base_url).replace(/(\/)$/, '');
        var headers   = {};
        for (var header in method.headers) {
            headers[header] = method.headers[header];
        }
        return simpleHttp.createRequest(this.httpClient, baseUrl + method.path, method.method, headers, params, payload);
    }
949208
public static JSONObject getJSONObject(HttpGet request, Integer method) throws JSONException {
        return UpworkRestClient.getJSONObject(request, method, new HashMap<String, String>());
    }
818728
public ApiResponse apiRequest(HttpMethod method,
            Map<String, Object> params, Object data, String... segments) {
        ApiResponse response = null;
        try {
            response = httpRequest(method, ApiResponse.class, params, data,
                    segments);
            log.info("Client.apiRequest(): Response: " + response);
        } catch (HttpClientErrorException e) {
            log.error("Client.apiRequest(): HTTP error: "
                    + e.getLocalizedMessage());
            response = parse(e.getResponseBodyAsString(), ApiResponse.class);
            if ((response != null) && !isEmpty(response.getError())) {
                log.error("Client.apiRequest(): Response error: "
                        + response.getError());
                if (!isEmpty(response.getException())) {
                    log.error("Client.apiRequest(): Response exception: "
                            + response.getException());
                }
            }
        }
        return response;
    }
1199981
function Request(method, url) {
  var self = this;
  this._query = this._query || [];
  this.method = method;
  this.url = url;
  this.header = {}; // preserves header name case
  this._header = {}; // coerces header names to lowercase
  this.on('end', function(){
    var err = null;
    var res = null;

    try {
      res = new Response(self);
    } catch(e) {
      err = new Error('Parser is unable to parse the response');
      err.parse = true;
      err.original = e;
      // issue #675: return the raw response if the response parsing fails
      err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null;
      // issue #876: return the http status code if the response parsing fails
      err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null;
      return self.callback(err);
    }

    self.emit('response', res);

    var new_err;
    try {
      if (res.status < 200 || res.status >= 300) {
        new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
        new_err.original = err;
        new_err.response = res;
        new_err.status = res.status;
      }
    } catch(e) {
      new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android
    }

    // #1000 don't catch errors from the callback to avoid double calling it
    if (new_err) {
      self.callback(new_err, res);
    } else {
      self.callback(null, res);
    }
  });
}
1006768
public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) {
    try {
      ServletUtils.startTransaction(request.getHeader("User-Agent"));

      // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters.
      String uri = request.getServletPath();

      Properties headers = new Properties();
      Enumeration<String> en = request.getHeaderNames();
      while (en.hasMoreElements()) {
        String key = en.nextElement();
        String value = request.getHeader(key);
        headers.put(key, value);
      }

      final String contentType = request.getContentType();
      Properties parms = new Properties();
      String postBody = null;
      if (System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors") != null) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      }

      if (contentType != null && contentType.startsWith(MIME_JSON)) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
          BufferedReader reader = request.getReader();
          while ((line = reader.readLine()) != null)
            jb.append(line);
        } catch (Exception e) {
          throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri);
        }
        postBody = jb.toString();
      } else {
        // application/x-www-form-urlencoded
        Map<String, String[]> parameterMap;
        parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
          String key = entry.getKey();
          String[] values = entry.getValue();

          if (values.length == 1) {
            parms.put(key, values[0]);
          } else if (values.length > 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean first = true;
            for (String value : values) {
              if (!first) sb.append(",");
              sb.append("\"").append(value).append("\"");
              first = false;
            }
            sb.append("]");
            parms.put(key, sb.toString());
          }
        }
      }

      // Make serve() call.
      NanoResponse resp = serve(uri, method, headers, parms, postBody);

      // Un-marshal Nano response back to Jetty.
      String choppedNanoStatus = resp.status.substring(0, 3);
      assert (choppedNanoStatus.length() == 3);
      int sc = Integer.parseInt(choppedNanoStatus);
      ServletUtils.setResponseStatus(response, sc);

      response.setContentType(resp.mimeType);

      Properties header = resp.header;
      Enumeration<Object> en2 = header.keys();
      while (en2.hasMoreElements()) {
        String key = (String) en2.nextElement();
        String value = header.getProperty(key);
        response.setHeader(key, value);
      }

      resp.writeTo(response.getOutputStream());

    } catch (IOException e) {
      e.printStackTrace();
      ServletUtils.setResponseStatus(response, 500);
      Log.err(e);
      // Trying to send an error message or stack trace will produce another IOException...
    } finally {
      ServletUtils.logRequest(method, request, response);
      // Handle shutdown if it was requested.
      if (H2O.getShutdownRequested()) {
        (new Thread() {
          public void run() {
            boolean [] confirmations = new boolean[H2O.CLOUD.size()];
            if (H2O.SELF.index() >= 0) {
              confirmations[H2O.SELF.index()] = true;
            }
            for(H2ONode n:H2O.CLOUD._memary) {
              if(n != H2O.SELF)
                new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call();
            }
            try { Thread.sleep(2000); }
            catch (Exception ignore) {}
            int failedToShutdown = 0;
            // shutdown failed
            for(boolean b:confirmations)
              if(!b) failedToShutdown++;
            Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now.");
            H2O.closeAll();
            H2O.exit(failedToShutdown);
          }
        }).start();
      }
      ServletUtils.endTransaction();
    }
  }