当前位置: 首页>>代码示例>>Java>>正文


Java HttpRequest.code方法代码示例

本文整理汇总了Java中com.github.kevinsawicki.http.HttpRequest.code方法的典型用法代码示例。如果您正苦于以下问题:Java HttpRequest.code方法的具体用法?Java HttpRequest.code怎么用?Java HttpRequest.code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.github.kevinsawicki.http.HttpRequest的用法示例。


在下文中一共展示了HttpRequest.code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: insert

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
private Status insert(String data) {
	HttpRequest hr = null;
	long costTime = 0L;
	try {
		hr = HttpRequest.post(WRITE_URL).connectTimeout(100 * 1000).readTimeout(100 * 1000);
		long startTime = System.nanoTime();
		hr.send(data);
		hr.code();
		long endTime = System.nanoTime();
		costTime = endTime - startTime;
	} catch (Exception e) {
		e.printStackTrace();
		return Status.FAILED(-1);
	}
	System.out.println(hr.body());
	if (hr.code() >= 200 && hr.code() < 300) {
		return Status.OK(costTime);
	} else {
		return Status.FAILED(costTime);
	}
}
 
开发者ID:dbiir,项目名称:ts-benchmark,代码行数:22,代码来源:InfluxDB.java

示例2: wsConvert

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
private double wsConvert(double amount, String fromUnifiedSymbol, String toUnifiedSymbol)
		throws HttpRequestException, Exception {
	String fromUnit = prep(fromUnifiedSymbol);
	String toUnit = prep(toUnifiedSymbol);

	String conversionUrl = amount + "/" + FROM + fromUnit + "/" + TO + toUnit;
	String url = BASE_URL + conversionUrl;
	System.out.println(url);

	HttpRequest request = HttpRequest.get(url).accept("application/json");

	if (request.code() != 200) {
		throw new Exception("Web service call returned " + request.code());
	}

	double decimal = 0;
	String body = request.body();
	if (body.startsWith("{")) {
		WebServiceConversion wsResponse = gson.fromJson(body, WebServiceConversion.class);

		decimal = getResultQuantity(wsResponse);
	} else {
		throw new Exception(body);
	}
	return decimal;
}
 
开发者ID:point85,项目名称:caliper,代码行数:27,代码来源:TestUnifiedCode.java

示例3: getResults

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
@Override
public CopyOnWriteArrayList<? extends SearchResult> getResults(String query) throws IOException {
    if (this.apiKey.isEmpty()) {
        throw new IOException("engines.google.auth.api-key in ./config/enquiry.conf must be set in order to search with Google!");
    }
    if (this.searchId.isEmpty()) {
        throw new IOException("engines.google.auth.search-id in ./config/enquiry.conf must be set in order to search with Google!");
    }
    final HttpRequest request = getRequest(query);
    if (request.code() != 200) {
        throw new IOException("An error occurred while attempting to get results from " + Texts.toPlain(this.getName()) + ", Error: " + request
                .code());
    } else if (request.isBodyEmpty()) {
        throw new IOException("An error occurred while attempting to get results from " + Texts.toPlain(this.getName()) + ", Error: Body is "
                + "empty.");
    }
    return new Gson().fromJson(request.body(), GoogleEngine.class).results;
}
 
开发者ID:InspireNXE,项目名称:Enquiry-Legacy,代码行数:19,代码来源:GoogleEngine.java

示例4: getTitleForURL

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
@Override
public String getTitleForURL(String url) {
	try {
		HttpRequest req = HttpRequest.get(url).accept("text/html").followRedirects(true);
		if (req.code() >= 400)
			return null;
		
		String[] splitContentType = req.contentType().split(";");
		for (int i = 0; i < splitContentType.length; i++) {
			splitContentType[i] = splitContentType[i].trim();
		}
		if (splitContentType[0].equals("text/html")) {
			Matcher m = TITLE_PATTERN.matcher(req.body());
			if (m.find()) {
				String title = m.group(1).replaceAll("\\s+", " ").trim();
				title = StringEscapeUtils.unescapeHtml4(title);
				return String.format("[%s]", title);
			}
		}
	} catch (Exception e) {
	}
	return null;
}
 
开发者ID:Shockah,项目名称:Skylark,代码行数:24,代码来源:DefaultURLAnnouncer.java

示例5: doInBackground

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
/**
 * Override this method to perform a computation on a background thread. The
 * specified parameters are the parameters passed to {@link #execute}
 * by the caller of this task.
 *
 * This method can call {@link #publishProgress} to publish updates
 * on the UI thread.
 *
 * @param comicNumber The parameters of the task.
 * @return A result, defined by the subclass of this task.
 * @see #onPreExecute()
 * @see #onPostExecute
 * @see #publishProgress
 */
@Override protected Comic doInBackground(Integer... comicNumber) {
    // Should only ever be a single comic number, so let's enforce it.
    if (comicNumber != null && comicNumber.length == 1) {
        HttpRequest request = HttpRequest.get(ComicUtil.getComicApiUrl(comicNumber[0]));
        if (request.code() == 200) {
            String response = request.body();
            request.disconnect();
            Gson gson = new Gson();
            Comic comicResponse = gson.fromJson(response, Comic.class);

            return comicResponse;
        } else {
            request.disconnect();
            return null;
        }
    }
    return null;
}
 
开发者ID:DavidTPate,项目名称:XKCD-Reader,代码行数:33,代码来源:ComicFragment.java

示例6: sendNotification

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
public int sendNotification(NotificationMessage msg) {
    String antennaUrl = "http://antenna." + cmsApiHost + ":8080/antenna/rest/notify/";
    log.info("sending notification on " + antennaUrl);
    HttpRequest request = HttpRequest.post(antennaUrl)
            .contentType("application/json").send(new Gson().toJson(msg));
    return request.code();
}
 
开发者ID:oneops,项目名称:oneops,代码行数:8,代码来源:OneOpsFacade.java

示例7: makeRequest

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
private static String makeRequest(OIDCAccountManager accountManager, String method, String url, String body, Account account,
                                  boolean doRetry, AccountManagerCallback<Bundle> callback)
        throws IOException, UserNotAuthenticatedWrapperException, AuthenticatorException, OperationCanceledException {


    String accessToken = accountManager.getAccessToken(account, callback);
    String cookies = accountManager.getCookies(account, callback);

    // Prepare an API request using the accessToken
    HttpRequest request = new HttpRequest(url, method);
    request = prepareApiRequest(request, accessToken, cookies);
    if (body != "") {
        request.send(body);
    }

    if (request.ok()) {
        return request.body();
    } else {
        int code = request.code();

        String requestContent = "empty body";
        try {
            requestContent = request.body();
        } catch (HttpRequest.HttpRequestException e) {
            //Nothing to do, the response has no body or couldn't fetch it
            e.printStackTrace();
        }

        if (doRetry && (code == HTTP_UNAUTHORIZED || code == HTTP_FORBIDDEN ||
                (code == HTTP_BAD_REQUEST && (requestContent.contains("invalid_grant") || requestContent.contains("Access Token not valid"))))) {
            // We're being denied access on the first try, let's renew the token and retry
            accountManager.invalidateAuthTokens(account);

            return makeRequest(accountManager, method, url, body, account, false, callback);
        } else {
            // An unrecoverable error or the renewed token didn't work either
            throw new IOException(request.code() + " " + request.message() + " " + requestContent);
        }
    }
}
 
开发者ID:tdb-alcorn,项目名称:defect-party,代码行数:41,代码来源:APIUtility.java

示例8: doInBackground

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
protected String doInBackground(String... params) {
    HttpRequest request = HttpRequest.get(UPLOAD_URL,true, params);
    Log.d("jabe", "开始上传 : " + request.url());
    if (request.code() == 200) {
        return request.body();
    } else {
        return request.code()+"";
    }
}
 
开发者ID:jabelai,项目名称:location-phonegap,代码行数:10,代码来源:LocationCacheService.java

示例9: validateTests

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
/**
 * Validates a batch of test outputs. The outputs are to be passed in as a JSONArray containing a JSONObject for
 * each test. Each test needs to contain the fields "id" and "output".
 *
 * @param tests The batch of tests to send to the server for verification.
 * @return A list of results, one for each of the sent tests.
 * @throws ServerError In case of a non-200 response code from the server.
 */
List<TestResult> validateTests(JSONArray tests) throws ServerError
{
    JSONObject data = new JSONObject();
    data.put("results", tests);
    data.put("client_id", clientid);

    HttpRequest req =
            HttpRequest.post(serveruri + "validate_tests").followRedirects(true).contentType("application/json").send(data.toString());

    if (req.badRequest() || req.code() == 401)
    {
        clientid = null;
        prefs.remove(CLIENT_ID_PREF);
        throw new ServerError();
    }

    JSONArray results = new JSONObject(req.body()).getJSONArray("results");
    List<TestResult> ret = new ArrayList<>(results.length());
    for (Object t : results)
    {
        JSONObject o = (JSONObject) t;
        ret.add(new TestResult(o.getString("test_id"), o.getBoolean("result_ok"), o.getString("error")));
    }

    return ret;
}
 
开发者ID:molguin92,项目名称:MoulinetteClient,代码行数:35,代码来源:MoulinetteServerManager.java

示例10: makeRequest

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
private static String makeRequest(OIDCAccountManager accountManager, String method, String url, Account account,
                                  boolean doRetry, AccountManagerCallback<Bundle> callback)
        throws IOException, UserNotAuthenticatedWrapperException, AuthenticatorException, OperationCanceledException {


    String accessToken = accountManager.getAccessToken(account, callback);

    // Prepare an API request using the accessToken
    HttpRequest request = new HttpRequest(url, method);
    request = prepareApiRequest(request, accessToken);

    if (request.ok()) {
        return request.body();
    } else {
        int code = request.code();

        String requestContent = "empty body";
        try {
            requestContent = request.body();
        } catch (HttpRequest.HttpRequestException e) {
            //Nothing to do, the response has no body or couldn't fetch it
            e.printStackTrace();
        }

        if (doRetry && (code == HTTP_UNAUTHORIZED || code == HTTP_FORBIDDEN ||
                (code == HTTP_BAD_REQUEST && (requestContent.contains("invalid_grant") || requestContent.contains("Access Token not valid"))))) {
            // We're being denied access on the first try, let's renew the token and retry
            accountManager.invalidateAuthTokens(account);

            return makeRequest(accountManager, method, url, account, false, callback);
        } else {
            // An unrecoverable error or the renewed token didn't work either
            throw new IOException(request.code() + " " + request.message() + " " + requestContent);
        }
    }
}
 
开发者ID:kalemontes,项目名称:OIDCAndroidLib,代码行数:37,代码来源:APIUtility.java

示例11: getResults

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
@Override
public CopyOnWriteArrayList<? extends SearchResult> getResults(String query) throws IOException {
    final HttpRequest request = getRequest(query);
    if (request.code() != 200) {
        throw new IOException("An error occurred while attempting to get results from " + Texts.toPlain(this.getName()) + ", Error: " + request
                .code());
    } else if (request.isBodyEmpty()) {
        throw new IOException("An error occurred while attempting to get results from " + Texts.toPlain(this.getName()) + ", Error: Body is "
                + "empty.");
    }
    return new Gson().fromJson(request.body(), DuckDuckGoEngine.class).results;
}
 
开发者ID:InspireNXE,项目名称:Enquiry-Legacy,代码行数:13,代码来源:DuckDuckGoEngine.java

示例12: getResults

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
@Override
public CopyOnWriteArrayList<? extends SearchResult> getResults(String query) throws IOException {
    if (this.accountKey.isEmpty()) {
        throw new IOException("engines.bing.auth.account-key in ./config/enquiry.conf must be set in order to search with Bing!");
    }
    final HttpRequest request = getRequest(query);
    if (request.code() != 200) {
        throw new IOException("An error occurred while attempting to get results from " + Texts.toPlain(this.getName()) + ", Error: " + request
                .code());
    } else if (request.isBodyEmpty()) {
        throw new IOException("An error occurred while attempting to get results from " + Texts.toPlain(this.getName()) + ", Error: Body is "
                + "empty.");
    }
    return new Gson().fromJson(request.body(), BingEngine.class).data.results;
}
 
开发者ID:InspireNXE,项目名称:Enquiry-Legacy,代码行数:16,代码来源:BingEngine.java

示例13: doInBackground

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
/**
 * Override this method to perform a computation on a background thread. The
 * specified parameters are the parameters passed to {@link #execute}
 * by the caller of this task.
 *
 * This method can call {@link #publishProgress} to publish updates
 * on the UI thread.
 *
 * @param params The parameters of the task.
 * @return A result, defined by the subclass of this task.
 * @see #onPreExecute()
 * @see #onPostExecute
 * @see #publishProgress
 */
@Override protected Comic doInBackground(Void... params) {
    HttpRequest request = HttpRequest.get(Constants.API.LATEST_COMIC_ENDPOINT);
    if (request.code() == 200) {
        String response = request.body();
        request.disconnect();
        Gson gson = new Gson();
        Comic comicResponse = gson.fromJson(response, Comic.class);

        return comicResponse;
    } else {
        request.disconnect();
        return null;
    }
}
 
开发者ID:DavidTPate,项目名称:XKCD-Reader,代码行数:29,代码来源:ComicFragmentActivity.java

示例14: getResponse

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
public static Response getResponse(final Request request, final HttpRequest httpRequest) throws IOException {
    // Execute request and get response
    final int responseCode = httpRequest.code();
    final String responseMessage = httpRequest.message();
    final String responseCharset = getValidCharSet(httpRequest);
    final byte[] bodyBytes = httpRequest.body().getBytes(responseCharset);

    // Prepare response headers
    Map<String, List<String>> httpRequestResponseHeaders = httpRequest.headers();
    List<Header> retrofitResponseHeaders = transformHttpResponseHeadersToRetrofitHeaders(httpRequestResponseHeaders);

    // Prepare response data
    TypedInput typedInput = new TypedInput() {
        @Override
        public String mimeType() {
            return httpRequest.contentType();
        }

        @Override
        public long length() {
            return bodyBytes.length;
        }

        @Override
        public InputStream in() throws IOException {
            return new ByteArrayInputStream(bodyBytes);
        }
    };

    // Response object for Retrofit
    return new Response(request.getUrl(), responseCode, responseMessage, retrofitResponseHeaders, typedInput);
}
 
开发者ID:groodt,项目名称:http-request-retrofit-client,代码行数:33,代码来源:HttpRequestClient.java

示例15: _save

import com.github.kevinsawicki.http.HttpRequest; //导入方法依赖的package包/类
/**
 *
 * @param client    The communication client
 * @return          The details of the subscription as a result of the save
 * @throws Exception
 */
public Response<Subscription> _save(Client client) throws Exception {
    HttpRequest request = this.isPersisted() ?
            client.put("subscriptions/" + id, this.asHash()) :
            client.post("subscriptions", this.asHash());
    return new Response<Subscription>(request.code(), request.body(), Subscription.class);
}
 
开发者ID:kfrancis,项目名称:Chargify.Java,代码行数:13,代码来源:Subscription.java


注:本文中的com.github.kevinsawicki.http.HttpRequest.code方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。