com.github.kevinsawicki.http.HttpRequest Java Examples

The following examples show how to use com.github.kevinsawicki.http.HttpRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpUtil.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 构造POST提交表单请求,返回响应结果
 * @param params
 * 提交的参数
 * @param address
 * 提交的地址
 * @param connectTimeout
 * @param readTimeout
 * @return
 */
public static HttpResult post(Map<String,String> params,String address,int connectTimeout,int readTimeout) throws IOException {
    HttpResult result = new HttpResult();
    if(params == null){
        params = new HashMap<>();
    }
    if(StringUtils.isEmpty(address)){
        log.error("请求地址不能为空");
        return null;
    }
    URL requestUrl = new URL(address);
    long start = System.currentTimeMillis();
    HttpRequest httpRequest = new HttpRequest(requestUrl,"POST")
            .connectTimeout(connectTimeout).readTimeout(readTimeout).trustAllCerts().trustAllHosts();
    httpRequest.form(params,"UTF-8");
    result.setStatus(httpRequest.code());
    result.setResult(httpRequest.body());
    result.setResponseTime(System.currentTimeMillis() - start);
    return result;
}
 
Example #2
Source File: RegistrationIntentService.java    From httpebble-android with MIT License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    if (!TextUtils.isEmpty(Settings.getEmail(this)) && !TextUtils.isEmpty(Settings.getToken(this))) {
        try {
            JSONObject data = new JSONObject();
            data.put("userId", Settings.getEmail(this));
            data.put("userToken", Settings.getToken(this));
            data.put("gcmId", InstanceID.getInstance(this).getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null));
            data.put("purchased", Settings.hasPurchased(this) || BuildConfig.DEBUG);

            int code = HttpRequest.post("https://ofkorth.net/pebble/register")
                    .send("data=" + data.toString())
                    .code();
            if (code == 200) {
                Settings.setNeedToRegister(this, false);
            } else {
                Settings.setNeedToRegister(this, true);
            }
        } catch (IOException | JSONException e) {
            Settings.setNeedToRegister(this, true);
        }
    }
}
 
Example #3
Source File: MonitoringAPI.java    From cloudml with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method upload the deployment model in the monitoring manager
 *
 * @param model the state of the deployment
 */
public void uploadDeployment(Model model){

    String url = address + "/" + version + "/model/resources";
    int result;
    Gson gson = new GsonBuilder().serializeNulls().create();
    String json = gson.toJson(model);
    try {
        journal.log(Level.INFO, ">> Connecting to the monitoring platform at "+address+"...");
    result = HttpRequest.put(url).send(json).code();
        printComponentname(model);
    } catch (Exception e) {
       result = 0;
    }

    printResult(result);

}
 
Example #4
Source File: MonitoringAPI.java    From cloudml with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method sends an update to the monitoring manager about the state of the deployment
 *
 * @param update the state of the deployment
 */
public void addInstances(Model update){

    String url = address + "/" + version + "/model/resources";
    int result;
    Gson gson = new GsonBuilder().serializeNulls().create();
    String json = gson.toJson(update);

    try {
        journal.log(Level.INFO, ">> Connecting to the monitoring platform at "+address+"...");
        printComponentname(update);
        result = HttpRequest.post(url).send(json).code();
    } catch (Exception e) {
    result = 0;
    }
    printResult(result);

}
 
Example #5
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 6 votes vote down vote up
/**
 * Gets user information from the UserInfo endpoint.
 * @param token an idToken or accessToken associated to the end-user.
 * @param classOfT the class used to deserialize the user info into.
 * @return the parsed user information.
 * @throws IOException for an error response
 */
public  <T> T getUserInfo(String token,  Class<T> classOfT) throws IOException {
    String url = userInfoEndpoint;
    if (extras != null) {
        url = HttpRequest.append(userInfoEndpoint, extras);
    }

    HttpRequest request = new HttpRequest(url, HttpRequest.METHOD_GET);
    request.authorization("Bearer " + token).acceptJson();

    if (request.ok()) {
        String jsonString = request.body();
        return new Gson().fromJson(jsonString, classOfT);
    } else {
        throw new IOException(request.message());
    }
}
 
Example #6
Source File: AbstractGithubFragment.java    From TwrpBuilder with GNU General Public License v3.0 6 votes vote down vote up
private void updateCache() {
    pushInfo(R.string.connecting_to_github);

    new Thread() {
        @Override
        public void run() {
            super.run();

            try {
                final StringBuilder result = new StringBuilder();

                HttpRequest httpRequest = HttpRequest.get(mTargetURL);
                httpRequest.receive(result);

                mAwaitedList = new JSONArray(result.toString());

                update();
            } catch (Exception e) {
                pushInfoWithThread();
                e.printStackTrace();
            }
        }
    }.start();
}
 
Example #7
Source File: SpotifyPlayer.java    From nanoleaf-desktop with MIT License 6 votes vote down vote up
private AudioAnalysis getTrackAnalysis(String trackId)
{
	HttpRequest req = HttpRequest.get("https://api.spotify.com/v1/audio-analysis/" + trackId);
	req.header("Content-Type", "application/json");
	req.header("Accept", "application/json");
	req.header("Authorization", "Bearer " + spotifyApi.getAccessToken());
	JSONObject json = new JSONObject(req.body());
	json.getJSONObject("meta").put("status_code", req.code());
	AudioAnalysisMeta aamet = new AudioAnalysisMeta.JsonUtil().createModelObject(json.getJSONObject("meta").toString());
	AudioAnalysisTrack aat = new AudioAnalysisTrack.JsonUtil().createModelObject(json.getJSONObject("track").toString());
	AudioAnalysisMeasure[] aamba = new AudioAnalysisMeasure.JsonUtil().createModelObjectArray(json.getJSONArray("bars").toString());
	AudioAnalysisMeasure[] aambe = new AudioAnalysisMeasure.JsonUtil().createModelObjectArray(json.getJSONArray("beats").toString());
	AudioAnalysisSection[] aasec = new AudioAnalysisSection.JsonUtil().createModelObjectArray(json.getJSONArray("sections").toString());
	AudioAnalysisSegment[] aaseg = new AudioAnalysisSegment.JsonUtil().createModelObjectArray(json.getJSONArray("segments").toString());
	AudioAnalysisMeasure[] aamta = new AudioAnalysisMeasure.JsonUtil().createModelObjectArray(json.getJSONArray("tatums").toString());
	return new AudioAnalysis.Builder()
			.setMeta(aamet)
			.setTrack(aat)
			.setBars(aamba)
			.setBeats(aambe)
			.setSections(aasec)
			.setSegments(aaseg)
			.setTatums(aamta)
			.build();
}
 
Example #8
Source File: HttpUtil.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 构造POST提交表单请求,返回响应结果
 * @param params
 * 提交的参数
 * @param address
 * 提交的地址
 * @param connectTimeout
 * @param readTimeout
 * @return
 */
public static HttpResult post(Map<String,String> params,String address,int connectTimeout,int readTimeout) throws IOException {
    HttpResult result = new HttpResult();
    if(params == null){
        params = new HashMap<>();
    }
    if(StringUtils.isEmpty(address)){
        log.error("请求地址不能为空");
        return null;
    }
    URL requestUrl = new URL(address);
    long start = System.currentTimeMillis();
    HttpRequest httpRequest = new HttpRequest(requestUrl,"POST")
            .connectTimeout(connectTimeout).readTimeout(readTimeout).trustAllCerts().trustAllHosts();
    httpRequest.form(params,"UTF-8");
    result.setStatus(httpRequest.code());
    result.setResult(httpRequest.body());
    result.setResponseTime(System.currentTimeMillis() - start);
    return result;
}
 
Example #9
Source File: Discovery.java    From nanoleaf-desktop with MIT License 6 votes vote down vote up
public static JSONObject getEffectsData(String type, int page, List<String> tags) {
    JSONObject json = null;
    while (json == null) {
        try {
            HttpRequest request = HttpRequest.get(String.format(
                    "%s/effects/%s?page=%d&tags=%s", BASE_ENDPOINT,
                    type, page, tagsToString(tags)));
            request.connectTimeout(20000);
            request.readTimeout(20000);
            return new JSONObject(request.body());
        } catch (JSONException je) {
            // do nothing, get json again
        }
    }
    return null;
}
 
Example #10
Source File: WontonController.java    From mcg-helper with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="getRule", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
   @ResponseBody
   public McgResult getRule(@Valid @RequestBody WontonHeart wontonHeart, HttpSession session) {
       McgResult mcgResult = new McgResult();
       
       try {
       	String rule = HttpRequest.get("http://" + wontonHeart.getInstancecode() + "/muxy/networkshapes")
       				.connectTimeout(Constants.REQUEST_WONTON_TIME_OUT).body();
       	mcgResult.addAttribute("rule", rule);
       } catch (Exception e) {
       	logger.error("获取混沌客户端规则出错,异常信息:{}", e.getMessage());
       	mcgResult.setStatusCode(0);
       	mcgResult.setStatusMes("获取混沌客户端规则异常!");
	}
   	return mcgResult;
}
 
Example #11
Source File: CanvasExtStreaming.java    From nanoleaf-desktop with MIT License 6 votes vote down vote up
public static void enable(Aurora aurora) throws StatusCodeException
{
	try
	{
		String body = "{\"write\": {\"command\": \"display\", \"animType\": " +
				"\"extControl\", \"extControlVersion\": \"v2\"}}";
		String url = String.format("http://%s:%d/api/%s/%s/%s",
				aurora.getHostName(), aurora.getPort(),
				aurora.getApiLevel(), aurora.getAccessToken(), "effects");
		HttpRequest req = HttpRequest.put(url);
		req.connectTimeout(2000);
		if (body != null)
			req.send(body);
		req.ok();
	}
	catch (HttpRequestException hre)
	{
		hre.printStackTrace();
	}
}
 
Example #12
Source File: HttpUtil.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 发送json post请求
 * @param url
 * @param data
 * @return
 * @throws IOException
 */
public static HttpResult postJSON(String url,String data,int connectTimeout,int readTimeout) throws IOException {
    HttpResult result = new HttpResult();
    long start = System.currentTimeMillis();
    HttpRequest httpRequest = new HttpRequest(new URL(url),"POST")
            .connectTimeout(connectTimeout).readTimeout(readTimeout)
            .acceptJson()
            .contentType("application/json","UTF-8")
            .send(data.getBytes("UTF-8"));

    result.setStatus(httpRequest.code());
    result.setResult(httpRequest.body());
    result.setResponseTime(System.currentTimeMillis() - start);
    return result;
}
 
Example #13
Source File: ExceptionManager.java    From COCOFramework with Apache License 2.0 5 votes vote down vote up
@Override
public void error(Exception e, Context ctx, Object source) {
    if (e instanceof CocoException || e instanceof HttpRequest.HttpRequestException)
        e.printStackTrace();
    else
        Log.e(e);
}
 
Example #14
Source File: ExceptionManager.java    From COCOFramework with Apache License 2.0 5 votes vote down vote up
@Override
public boolean exception(Exception e, Context ctx, Object source) throws CocoException {
    if (e instanceof CocoException || e instanceof HttpRequest.HttpRequestException)
        e.printStackTrace();
    else
        Log.e(e);
    return false;
}
 
Example #15
Source File: MonitoringAPI.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method tells to the monitoring manager which instances must be removed
 * from the deployment model
 *
 * @param id are the IDs of the instances to be deleted
 * @return int code status of the connection
 */
public int deleteInstances(String id){
    String url = address + "/" + version + "/model/resources/" + id;
    int result;
    try {
        journal.log(Level.INFO, ">> Connecting to the monitoring platform at "+address+"...");
        result = HttpRequest.delete(url).code();
    } catch (Exception e) {
        result = NO_RESPONSE;
    }
    printResult(result);

    return result;
}
 
Example #16
Source File: Discovery.java    From nanoleaf-desktop with MIT License 5 votes vote down vote up
public static Effect downloadEffect(String key) {
    HttpRequest request = HttpRequest.get(String.format("%s/effects/download/%s",
                                                        BASE_ENDPOINT, key));
    request.connectTimeout(10000);
    request.readTimeout(10000);
    return Effect.fromJSON(request.body());
}
 
Example #17
Source File: MonitoringAPI.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method sends a request to attach an observer to a specific metric
 * @param callback the address on which the observer is running
 *
 * @param metric the requested metric
 */
public void attachObserver(String callback, String metric) {

    String url = address + "/" + version + "/metrics/" + metric + "/observers";
    try {
    HttpRequest.post(url).send(callback).code();
           journal.log(Level.INFO, "Observer attached");
    } catch (Exception e) {
        journal.log(Level.INFO, "Connection to the monitoring manager refused");
    }



}
 
Example #18
Source File: MonitoringAPI.java    From cloudml with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method sends a request to upload a monitoring rule to the monitoring manager.
 @param rule is the monitoring rule to be uploaded

 @return the response of the monitoring manager
 */
public String addMonitoringRule(String rule){

    String url = address + "/" + version + "/monitoring-rules";
    String response = null;

    try {
        response = HttpRequest.post(url).send(rule).body();
    } catch (Exception e) {
        journal.log(Level.INFO, "Connection to the monitoring manager refused");
    }
    return response;
}
 
Example #19
Source File: GoogleChartDotWriter.java    From dot-diagram with Apache License 2.0 5 votes vote down vote up
@Override
public void render(String filename) throws InterruptedException, IOException {
    String dot = read(path + filename + ".dot");
    HttpRequest httpRequest = HttpRequest.get(GOOGLE_CHART_API, true, "cht", "gv", "chl", dot);
    if (httpRequest.ok()) {
        try (InputStream is = httpRequest.stream()) {
            Files.copy(is, Paths.get(path + filename + getImageExtension()));
        }
    } else {
        throw new DotDiagramException("Errors calling Graphviz chart.googleapis.com");
    }
}
 
Example #20
Source File: WontonController.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/recoveryNet")
  @ResponseBody
  public McgResult recoveryNet(String instanceCode, HttpSession session) throws Exception {

      McgResult mcgResult = new McgResult();
      
  	try {
  		
  		String url = String.format("http://%s/muxy/networkshape/_disable", instanceCode);
  		HttpRequest httpRequest = HttpRequest.put(url).connectTimeout(Constants.REQUEST_WONTON_TIME_OUT);
  		String result = httpRequest.body();
  		
  		if(StringUtils.isNotEmpty(result) && result.endsWith("successfully")) {
      		mcgResult.setStatusCode(1);
      		mcgResult.setStatusMes(instanceCode + "网络恢复成功!");
  		} else {
      		mcgResult.setStatusCode(0);
      		mcgResult.setStatusMes(instanceCode + "网络恢复失败!");
  		}
  	} catch (Exception e) {
  		String reason = instanceCode + "网络恢复失败!";
	logger.error(reason + "异常信息:{}", e.getMessage());
  		mcgResult.setStatusCode(0);
  		mcgResult.setStatusMes(reason);
}

      return mcgResult;
  }
 
Example #21
Source File: DebugUtil.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
private static String uploadToBin(String binHost, int aesBits, List<Map<String, String>> files, String description) {
    String key = RandomStringUtils.randomAlphanumeric(aesBits == 256 ? 32 : 16);
    byte[] keyBytes = key.getBytes();

    // decode to bytes, encrypt, base64
    List<Map<String, String>> encryptedFiles = new ArrayList<>();
    for (Map<String, String> file : files) {
        Map<String, String> encryptedFile = new HashMap<>(file);
        encryptedFile.entrySet().removeIf(entry -> StringUtils.isBlank(entry.getValue()));
        encryptedFile.replaceAll((k, v) -> b64(encrypt(keyBytes, file.get(k))));
        encryptedFiles.add(encryptedFile);
    }

    Map<String, Object> payload = new HashMap<>();
    payload.put("description", b64(encrypt(keyBytes, description)));
    payload.put("expiration", TimeUnit.DAYS.toMinutes(1));
    payload.put("files", encryptedFiles);
    HttpRequest request = HttpRequest.post(binHost + "/v1/post")
            .userAgent("DiscordSRV " + DiscordSRV.version)
            .send(GSON.toJson(payload));
    if (request.code() == 200) {
        Map json = GSON.fromJson(request.body(), Map.class);
        if (json.get("status").equals("ok")) {
            return binHost + "/" + json.get("bin") + "#" + key;
        } else {
            String reason = "";
            if (json.containsKey("error")) {
                Map error = (Map) json.get("error");
                reason = ": " + error.get("type") + " " + error.get("message");
            }
            throw new RuntimeException("Bin upload status wasn't ok" + reason);
        }
    } else {
        throw new RuntimeException("Got bad HTTP status from Bin: " + request.code());
    }
}
 
Example #22
Source File: WontonController.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/recoveryHardware")
  @ResponseBody
  public McgResult recoveryHardware(String instanceCode, HttpSession session) throws Exception {
      McgResult mcgResult = new McgResult();
      
  	try {
  		
  		String url = String.format("http://%s/stressng/stressors", instanceCode);
  		HttpRequest httpRequest = HttpRequest.delete(url).connectTimeout(Constants.REQUEST_WONTON_TIME_OUT);
  		String result = httpRequest.body();
  		
  		if(StringUtils.isNotEmpty(result) && result.endsWith("here\n")) {
      		mcgResult.setStatusCode(1);
      		mcgResult.setStatusMes(instanceCode + "没有启动cpu、io、内存规则,不用恢复!");
  		} else {
      		mcgResult.setStatusCode(0);
      		mcgResult.setStatusMes(instanceCode + "硬件恢复失败!");
  		}
  	} catch (Exception e) {
	
  		String reason = instanceCode + "禁用cpu、io、内存规则,恢复硬件资源性能失败!";
  		logger.error(reason + "异常信息:{}", e.getMessage());
  		mcgResult.setStatusCode(0);
  		mcgResult.setStatusMes(reason);
}

      return mcgResult;
  }
 
Example #23
Source File: HttpUtil.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 发送json post请求
 * @param url
 * @param connectTimeout
 * @param readTimeout
 * @return
 * @throws IOException
 */
public static HttpResult get(String url,int connectTimeout,int readTimeout) throws IOException {
    HttpResult result = new HttpResult();

    if(!StringUtils.isEmpty(url)){
        URL requestUrl = new URL(url);
        long start = System.currentTimeMillis();
        HttpRequest httpRequest = new HttpRequest(requestUrl,"GET")
                .connectTimeout(connectTimeout).readTimeout(readTimeout).trustAllCerts().trustAllHosts();
        result.setStatus(httpRequest.code());
        result.setResult(httpRequest.body());
        result.setResponseTime(System.currentTimeMillis() - start);
    }
    return result;
}
 
Example #24
Source File: HttpUtil.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 发送json post请求
 * @param url
 * @param data
 * @return
 * @throws IOException
 */
public static HttpResult postJSON(String url,String data,int connectTimeout,int readTimeout) throws IOException {
    HttpResult result = new HttpResult();
    long start = System.currentTimeMillis();
    HttpRequest httpRequest = new HttpRequest(new URL(url),"POST")
            .connectTimeout(connectTimeout).readTimeout(readTimeout)
            .acceptJson()
            .contentType("application/json","UTF-8")
            .send(data.getBytes("UTF-8"));

    result.setStatus(httpRequest.code());
    result.setResult(httpRequest.body());
    result.setResponseTime(System.currentTimeMillis() - start);
    return result;
}
 
Example #25
Source File: HttpUtil.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 发送json post请求
 * @param url
 * @param connectTimeout
 * @param readTimeout
 * @return
 * @throws IOException
 */
public static HttpResult get(String url,int connectTimeout,int readTimeout) throws IOException {
    HttpResult result = new HttpResult();

    if(!StringUtils.isEmpty(url)){
        URL requestUrl = new URL(url);
        long start = System.currentTimeMillis();
        HttpRequest httpRequest = new HttpRequest(requestUrl,"GET")
                .connectTimeout(connectTimeout).readTimeout(readTimeout).trustAllCerts().trustAllHosts();
        result.setStatus(httpRequest.code());
        result.setResult(httpRequest.body());
        result.setResponseTime(System.currentTimeMillis() - start);
    }
    return result;
}
 
Example #26
Source File: UpdateManager.java    From nanoleaf-desktop with MIT License 4 votes vote down vote up
protected String getResponseFrom(String host) {
	return HttpRequest.get(host).body();
}
 
Example #27
Source File: MonitoringAPI.java    From cloudml with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * This methods sends a request to get all the metrics available
 *
 * @return a list of metrics
 */
public List<String> getMetrics(){

    String url = address + "/" + version + "/metrics";

    try {
        String response = HttpRequest.get(url).body();
    } catch (Exception e) {
        journal.log(Level.INFO, "Connection to the monitoring manager refused");
        return null;
    }



    //TODO parse results

    return null;
}
 
Example #28
Source File: LazyLoadManager.java    From GiraffePlayer2 with Apache License 2.0 4 votes vote down vote up
@Override
protected void onHandleIntent(@Nullable Intent intent) {
    String fingerprint = intent.getStringExtra(KEY_FINGERPRINT);
    log(fingerprint, "loadStatus:" + loadStatus);
    if (loadStatus > 0) {
        sendLastMessage();
        return;
    }
    loadStatus = STATUS_LOADING;
    //https://raw.githubusercontent.com/tcking/GiraffePlayerLazyLoadFiles/master/0.1.17/armeabi/so.zip
    Context context = getApplicationContext();
    try {
        File playerDir = getPlayerRootDir(context);
        File soDir = getPlayerSoDir(context);
        log(fingerprint,"soDir:"+soDir);
        if (new File(soDir, "libijkffmpeg.so").exists()) {
            log(fingerprint,"so files downloaded,try install");
            installSo(soDir);
            return;
        }

        String abi = getCurrentAbi(context);
        String url = soFetcher.getURL(abi, soVersion);
        log(fingerprint, "download so from:" + url);
        progress = -1;
        HttpRequest request = HttpRequest.get(url);
        int code = request.code();
        log(fingerprint, "server:" + code);
        if (code == HttpURLConnection.HTTP_OK) {
            File tmp = new File(new File(playerDir, "tmp"), "so.zip");
            tmp.delete();
            tmp.getParentFile().mkdirs();
            tmp.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(tmp);
            BufferedInputStream buffer = request.buffer();
            byte data[] = new byte[4096];
            long total = 0;
            int count;
            int contentLength = request.contentLength();
            while ((count = buffer.read(data)) != -1) {
                total += count;
                // publishing the progress....
                if (contentLength > 0) {
                    publishProgress((int) (total * 100 / contentLength));
                }
                fileOutputStream.write(data, 0, count);
            }
            fileOutputStream.close();

            unZip(tmp, soDir);
            tmp.delete();
            installSo(soDir);
        } else {
            error("server response " +code);
        }
    } catch (Exception e) {
        e.printStackTrace();
        error(e.getMessage());
    }


}