Tabnine Logo
OkHttpClient.newCall
Request$Builder.post
Code IndexAdd Tabnine to your IDE (free)

How to use
newCall
method
in
okhttp3.OkHttpClient

Making http post requests using okhttp

origin: square/okhttp

String post(String url, String json) throws IOException {
 RequestBody body = RequestBody.create(JSON, json);
 Request request = new Request.Builder()
   .url(url)
   .post(body)
   .build();
 try (Response response = client.newCall(request).execute()) {
  return response.body().string();
 }
}
origin: square/okhttp

public void run() throws Exception {
 File file = new File("README.md");
 Request request = new Request.Builder()
   .url("https://api.github.com/markdown/raw")
   .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
   .build();
 try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  System.out.println(response.body().string());
 }
}
origin: square/okhttp

public void run() throws Exception {
 Map<String, String> requestBody = new LinkedHashMap<>();
 requestBody.put("longUrl", "https://publicobject.com/2014/12/04/html-formatting-javadocs/");
 RequestBody jsonRequestBody = RequestBody.create(
   MEDIA_TYPE_JSON, mapJsonAdapter.toJson(requestBody));
 Request request = new Request.Builder()
   .url("https://www.googleapis.com/urlshortener/v1/url?key=" + GOOGLE_API_KEY)
   .post(jsonRequestBody)
   .build();
 try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  System.out.println(response.body().string());
 }
}
origin: square/okhttp

public void run() throws Exception {
 String postBody = ""
   + "Releases\n"
   + "--------\n"
   + "\n"
   + " * _1.0_ May 6, 2013\n"
   + " * _1.1_ June 15, 2013\n"
   + " * _1.2_ August 11, 2013\n";
 Request request = new Request.Builder()
   .url("https://api.github.com/markdown/raw")
   .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
   .build();
 try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  System.out.println(response.body().string());
 }
}
origin: square/okhttp

public void run() throws Exception {
 final PipeBody pipeBody = new PipeBody();
 Request request = new Request.Builder()
   .url("https://api.github.com/markdown/raw")
   .post(pipeBody)
   .build();
 streamPrimesToSinkAsynchronously(pipeBody.sink());
 try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  System.out.println(response.body().string());
 }
}
origin: square/okhttp

public void run() throws Exception {
 RequestBody formBody = new FormBody.Builder()
   .add("search", "Jurassic Park")
   .build();
 Request request = new Request.Builder()
   .url("https://en.wikipedia.org/w/index.php")
   .post(formBody)
   .build();
 try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  System.out.println(response.body().string());
 }
}
origin: square/okhttp

public void run() throws Exception {
 RequestBody requestBody = new RequestBody() {
  @Override public MediaType contentType() {
   return MEDIA_TYPE_MARKDOWN;
  }
  @Override public void writeTo(BufferedSink sink) throws IOException {
   sink.writeUtf8("Numbers\n");
   sink.writeUtf8("-------\n");
   for (int i = 2; i <= 997; i++) {
    sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
   }
  }
  private String factor(int n) {
   for (int i = 2; i < n; i++) {
    int x = n / i;
    if (x * i == n) return factor(x) + " × " + i;
   }
   return Integer.toString(n);
  }
 };
 Request request = new Request.Builder()
   .url("https://api.github.com/markdown/raw")
   .post(requestBody)
   .build();
 try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  System.out.println(response.body().string());
 }
}
origin: square/okhttp

public void run() throws Exception {
 // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
 RequestBody requestBody = new MultipartBody.Builder()
   .setType(MultipartBody.FORM)
   .addFormDataPart("title", "Square Logo")
   .addFormDataPart("image", "logo-square.png",
     RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
   .build();
 Request request = new Request.Builder()
   .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
   .url("https://api.imgur.com/3/image")
   .post(requestBody)
   .build();
 try (Response response = client.newCall(request).execute()) {
  if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  System.out.println(response.body().string());
 }
}
origin: yu199195/Raincat

public String post(String url,String json) throws IOException {
  OkHttpClient client = new OkHttpClient();
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}
origin: apache/flink

public void send(DatadogHttpReporter.DatadogHttpRequest request) throws Exception {
  String postBody = serialize(request.getSeries());
  Request r = new Request.Builder()
    .url(seriesUrl)
    .post(RequestBody.create(MEDIA_TYPE, postBody))
    .build();
  client.newCall(r).enqueue(EmptyCallback.getEmptyCallback());
}
origin: graphhopper/graphhopper

protected String postJson(String url, JsonNode data) throws IOException {
  Request okRequest = new Request.Builder().url(url).post(RequestBody.create(MT_JSON, data.toString())).build();
  ResponseBody body = null;
  try {
    body = downloader.newCall(okRequest).execute().body();
    return body.string();
  } finally {
    Helper.close(body);
  }
}
origin: yu199195/hmily

/**
 * Post string.
 *
 * @param url  the url
 * @param json the json
 * @return the string
 * @throws IOException the io exception
 */
public String post(final String url, final String json) throws IOException {
  OkHttpClient client = new OkHttpClient();
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}
origin: SonarSource/sonarqube

 @Override
 public Void call(String url) throws Exception {
  okhttp3.Request request = new okhttp3.Request.Builder()
   .post(RequestBody.create(null, new byte[0]))
   .url(url + "?level=" + newLogLevel.name())
   .build();
  try (okhttp3.Response response = new OkHttpClient().newCall(request).execute()) {
   if (response.code() != 200) {
    throw new IOException(
     String.format(
      "Failed to change log level in Compute Engine. Code was '%s' and response was '%s' for url '%s'",
      response.code(),
      response.body().string(),
      url));
   }
   return null;
  }
 }
}
origin: SonarSource/sonarqube

/**
 * Inspired by https://github.com/square/okhttp/blob/parent-3.6.0/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L286
 */
private Response followPostRedirect(Response response) throws IOException {
 String location = response.header("Location");
 if (location == null) {
  throw new IllegalStateException(format("Missing HTTP header 'Location' in redirect of %s", response.request().url()));
 }
 HttpUrl url = response.request().url().resolve(location);
 // Don't follow redirects to unsupported protocols.
 if (url == null) {
  throw new IllegalStateException(format("Unsupported protocol in redirect of %s to %s", response.request().url(), location));
 }
 Request.Builder redirectRequest = response.request().newBuilder();
 redirectRequest.post(response.request().body());
 response.body().close();
 return okHttpClient.newCall(redirectRequest.url(url).build()).execute();
}
origin: Graylog2/graylog2-server

@Override
public void call(final Stream stream, final AlertCondition.CheckResult result) throws AlarmCallbackException {
  final Map<String, Object> event = Maps.newHashMap();
  event.put("stream", stream);
  event.put("check_result", result);
  final byte[] body;
  try {
    body = objectMapper.writeValueAsBytes(event);
  } catch (JsonProcessingException e) {
    throw new AlarmCallbackException("Unable to serialize alarm", e);
  }
  final String url = configuration.getString(CK_URL);
  final HttpUrl httpUrl = HttpUrl.parse(url);
  if (httpUrl == null) {
    throw new AlarmCallbackException("Malformed URL: " + url);
  }
  final Request request = new Request.Builder()
      .url(httpUrl)
      .post(RequestBody.create(CONTENT_TYPE, body))
      .build();
  try (final Response r = httpClient.newCall(request).execute()) {
    if (!r.isSuccessful()) {
      throw new AlarmCallbackException("Expected successful HTTP response [2xx] but got [" + r.code() + "].");
    }
  } catch (IOException e) {
    throw new AlarmCallbackException(e.getMessage(), e);
  }
}
origin: yaphone/itchat4j

public static boolean sendQrPicToServer(String username, String password, String uploadUrl, String localPath)
    throws IOException {
  File file = new File(localPath);
  RequestBody requestBody = new MultipartBody.Builder().addFormDataPart("username", username)
      .addFormDataPart("password", password)
      .addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)).build();
  Request request = new Request.Builder().url(uploadUrl).post(requestBody).build();
  Call call = client.newCall(request);
  try {
    Response response = call.execute();
    System.out.println(response.body().string());
  } catch (IOException e) {
    e.printStackTrace();
  }
  return true;
}
origin: runelite/runelite

public boolean submitQp(String username, int qp) throws IOException
{
  HttpUrl url = RuneLiteAPI.getApiBase().newBuilder()
    .addPathSegment("chat")
    .addPathSegment("qp")
    .addQueryParameter("name", username)
    .addQueryParameter("qp", Integer.toString(qp))
    .build();
  Request request = new Request.Builder()
    .post(RequestBody.create(null, new byte[0]))
    .url(url)
    .build();
  try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute())
  {
    return response.isSuccessful();
  }
}
origin: runelite/runelite

public boolean submitPb(String username, String boss, int pb) throws IOException
{
  HttpUrl url = RuneLiteAPI.getApiBase().newBuilder()
    .addPathSegment("chat")
    .addPathSegment("pb")
    .addQueryParameter("name", username)
    .addQueryParameter("boss", boss)
    .addQueryParameter("pb", Integer.toString(pb))
    .build();
  Request request = new Request.Builder()
    .post(RequestBody.create(null, new byte[0]))
    .url(url)
    .build();
  try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute())
  {
    return response.isSuccessful();
  }
}
origin: runelite/runelite

public boolean submitKc(String username, String boss, int kc) throws IOException
{
  HttpUrl url = RuneLiteAPI.getApiBase().newBuilder()
    .addPathSegment("chat")
    .addPathSegment("kc")
    .addQueryParameter("name", username)
    .addQueryParameter("boss", boss)
    .addQueryParameter("kc", Integer.toString(kc))
    .build();
  Request request = new Request.Builder()
    .post(RequestBody.create(null, new byte[0]))
    .url(url)
    .build();
  try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute())
  {
    return response.isSuccessful();
  }
}
origin: facebook/stetho

  .url(server.url("/"))
  .addHeader("Content-Encoding", "gzip")
  .post(compressedBody)
  .build();
Response response = mClientWithInterceptor.newCall(request).execute();
okhttp3OkHttpClientnewCall

Javadoc

Prepares the request to be executed at some point in the future.

Popular methods of OkHttpClient

  • <init>
  • newBuilder
  • dispatcher
  • connectionPool
  • newWebSocket
    Uses request to connect a new web socket.
  • cache
  • connectTimeoutMillis
    Default connect timeout (in milliseconds).
  • interceptors
    Returns an immutable list of interceptors that observe the full span of each call: from before the c
  • readTimeoutMillis
    Default read timeout (in milliseconds).
  • proxy
  • networkInterceptors
    Returns an immutable list of interceptors that observe a single network request and response. These
  • cookieJar
  • networkInterceptors,
  • cookieJar,
  • sslSocketFactory,
  • writeTimeoutMillis,
  • followRedirects,
  • hostnameVerifier,
  • retryOnConnectionFailure,
  • authenticator,
  • connectionSpecs

Popular in Java

  • Updating database using SQL prepared statement
  • getContentResolver (Context)
  • getResourceAsStream (ClassLoader)
  • getSystemService (Context)
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • IOException (java.io)
    Signals a general, I/O-related error. Error details may be specified when calling the constructor, a
  • ServletException (javax.servlet)
    Defines a general exception a servlet can throw when it encounters difficulty.
  • HttpServlet (javax.servlet.http)
    Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A sub
  • XPath (javax.xml.xpath)
    XPath provides access to the XPath evaluation environment and expressions. Evaluation of XPath Expr
  • DateTimeFormat (org.joda.time.format)
    Factory that creates instances of DateTimeFormatter from patterns and styles. Datetime formatting i
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now