Skip to content

Instantly share code, notes, and snippets.

@wispborne
Created March 23, 2017 10:39
Show Gist options
  • Save wispborne/af1566f58197d943fcc4570431c3edc7 to your computer and use it in GitHub Desktop.
Save wispborne/af1566f58197d943fcc4570431c3edc7 to your computer and use it in GitHub Desktop.
public void onCreate() {
// Http client
OkHttpClient client = new OkHttpClient();
// Content type
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// Whatever you want to send, here it's json
RequestBody body = RequestBody.create(JSON, yourJsonString);
// The request, you can add headers here too
Request request = new Request.Builder()
.url(yourUrl)
.header(name, value)
.header(name2, value2) // Can remove these headers if not needed
.post(body)
.build();
new Thread(new Runnable() {
@Override
public void run() {
Response response = client.newCall(request).execute();
// Switch to the UI thread. Not needed for Log.d, but if you want
// to print the response on the UI you'll need to be on the main thread
runOnUiThread(new Runnable() {
@Override
public void run() {
// Print the response (or change the UI)
Log.d(response.body().string());
}
});
}
}
}
@wispborne
Copy link
Author

Don't forget to add compile 'com.squareup.okhttp3:okhttp:3.6.0' to your app/build.gradle file.

@uhw76tgwquerhjbqwnejk
Copy link

I'll be trying this soon, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment