本文整理汇总了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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
示例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);
}
}
}
示例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()+"";
}
}
示例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;
}
示例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);
}
}
}
示例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;
}
示例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;
}
示例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;
}
}
示例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);
}
示例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);
}