I am using an API which uploads some data to the server, I am deploying this on android application.
I tested APIs using Postman and it works absolutely fine and generated code from postman
login code:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("username","abc#abc.com")
.addFormDataPart("password","E1234567")
.build();
Request request = new Request.Builder()
.url("192.168.1.51/auth/login")
.method("POST", body)
.addHeader("User-Agent", "Koala Admin")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
.build();
Response response = client.newCall(request).execute();
create user and upload photo
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("subject_type","1")
.addFormDataPart("name","jasim")
.addFormDataPart("start_time","1619496549")
.addFormDataPart("end_time","1619525349")
.addFormDataPart("photo","/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg")))
.build();
Request request = new Request.Builder()
.url("192.168.1.51/subject/file")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
.build();
Response response = client.newCall(request).execute();
Now I want to know that how can I put these code in AsyncTask class and make the necessary code in background.
You can call enqueue method instead of execute and it will work on the background thread:
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
// handle your response
}
#Override
public void onFailure(Call call, IOException e) {
// handle the failure
}
});
Related
How can I pass parameter with "--data {json}" on okHttp3? Do I need to add it in the headers like below? Or its not on the header, it need to be on another object?
Request request = new Request.Builder()
.header("Content-Type", "application/json; charset=utf-8")
.addHeader("data", "{json}")
.url(url)
Please let me know.
You must add to RequestBody :
final String BOUNDARY = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new MultipartBody.Builder(BOUNDARY)
.setType(MultipartBody.FORM)
.addFormDataPart("data", JsonData)
//.addFormDataPart("otherPara", otherPara)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
I am using an OkHttp Client for my Webservice call, its working successfully with JAVA Main function and returning response.
Now, I want to call this client from Postman; but I dont know what URL Shall i call? Like in jersey we create a base URL from #PATH annotation in Spring we use #service. What shall be done in okhttp to create a base url to call? Please help.
public String soapCaller() throws IOException, JSONException {
Response response = null;
try {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=0146b9a4-7e99-4c83-8e9e-6049cfec55da&client_secret=cJ5nD0yJ4fV8eM1nU4tK2yI5wQ0lG6iE7cP5bD4lQ8dB0jS6pV&scope=ABLApis");
Request request = new Request.Builder()
.url("https://uat-api.abl.com/abl-api/uat/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("accept", "application/json")
.build();
response = client.newCall(request).execute();
}
catch(Exception e)
{
logger.info("e: " + e);
}
return response.toString();
}
}
with Jersey Annotations
#GET
#Path("/fundTransfer")
#Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String soapCaller() throws IOException, JSONException {
/////////////////////////////
Response response = null;
try {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=0146b9a4-7e99-4c83-8e9e-6049cfec55da&client_secret=cJ5nD0yJ4fV8eM1nU4tK2yI5wQ0lG6iE7cP5bD4lQ8dB0jS6pV&scope=ABLApis");
Request request = new Request.Builder()
.url("https://uat-api.abl.com/abl-api/uat/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("accept", "application/json")
.build();
response = client.newCall(request).execute();
}
catch(Exception e)
{
logger.info("e: " + e);
}
///////////////////////////////////////////
return response.toString();
}
}
I make a post request using okHttp with the next code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
The server response with:
response
{
message: {
user: {
id: 12,
name: 'myName'
},
message: 'Usuario creado con éxito.',
code: 200
}
}
But the response that okHttp gives me is:
Response{protocol=http/1.1, code=200, message=OK, url=http://localhost:2222/api/users}
There isn´t a way to get what the server sends me with okHttp?
If the response is sent in the body you can get it with:
response.body().string();
You just had to look on the documentation
¡Salud!
What you are getting is the header of response object. you can access the body of response by:
response.body().string();
full code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
String responseBody = response.body().string();
I have an API to retrieve videos from our server, the API use the POST method and needs Authorization for Headers and deviceInfo for body parameter.
example.
URL: https://myapi.com/api/pretty_video.mp4
BODY: deviceInfo = device info
HEADER: Authorization: Bearer "Token"
METHOD: POST
I can't find any example of ExoPlayer using POST method in playing videos from URL.
SOLVED!
I solved it by using OkHttp.
DefaultBandwidthMeter defaultBandwidthMeter = new DefaultBandwidthMeter();
DataSource.Factory dataSourceFactory = new OkHttpDataSourceFactory(new OkHttpClient
.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1,TimeUnit.MINUTES)
.retryOnConnectionFailure(false)
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");
RequestBody requestBody = RequestBody.create(CONTENT_TYPE,"deviceinfo=12345");
Request request = chain.request().newBuilder()
.post(requestBody) . // HERE IS THE KEY
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer " + auth)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
return chain.proceed(request);
}
})
.build(), Util.getUserAgent(context,context.getString(R.string.app_name)), defaultBandwidthMeter);
I need your help, i'd like to know if there is a way to post a FormDataMultiPart with okHttp.
I know you're gonna say that there already are responses.
This is my case :
// Resource
#Consume(FORMDATAMULTIPART)
public Response getMultiPart(FormDataMultiPart multipart) {
return response.ok(service.postMultiPart(multipart);
}
// Service
public void postMultiPart(FormDataMultiPart multiPart) {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder() {
.url(URL)
.post(multiPart)
}
I know that post only get RequestBody and this is my question, do you know guys a way to convert the FormDataMultiPart to RequestBody??
Thanks a lot
In the Service change this part of the code
final Request request = new Request.Builder() {
.url(URL)
.post(multiPart)
to (assuming i'm sending a file) and use RequestBuilder
File file; // This is the file I want to send.
MediaType mediaType = MediaType.parse("multipart/form-data");
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("key", "name", RequestBody.create(mediaType, file)).build();
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder()
.headers(headerBuild)
.url(url);
requestBuilder.post(requestBody);
okhttp3.Request request = requestBuilder.build();
Have a look at MediaType which has been added in the above code.