Uploading image on imgur results OK, but no data - java

I'm trying to upload images from my android apk.
I use this code, seems works, but I getting no data response
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("image", getBase64Image(bitmapImage))
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("https://api.imgur.com/3/image")
.method("POST", body)
.addHeader("Authorization", "Client-ID " + CLIENT_ID)
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.d("ERROR",e.getMessage());
}
#Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
//My code
}
});

Related

GET Request returning 403 Forbidden but works on apitester?

I am trying to get the responce from the server but it is returinig 403 forbidden but testing api on apitester.com works.
This is the code how i am reqesting the get method :
public void getResponse(Context context) throws IOException {
OkHttpClient client = new OkHttpClient();
Hmac hmac = new Hmac();
String auth = hmac.txt;
String url = "https://api.hotstar.com/h/v1/play?contentId=1000034502";
Request request = new Request.Builder()
.url(url)
.addHeader("hotstarauth",auth)
.addHeader("referer","https://hotstar.com/movies/2-states/1000034502")
.addHeader("x-country-code","IN")
.addHeader("x-platform-code","TABLET")
.addHeader("x-region-code","undefined")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("Server Responded: ", response.toString());
}
});
}
and in response i am getting 403 FORBIDDEN
but using the same config on apitester.com it works !
here is the sharedconig on apitester https://www.apitester.com/shared/checks/dca814bb92fb40af8aecda95cdf2f39c
why i am not getting the response on android ?

500, Internal Server Error in Retrofit 2

I have 500 internal server error, every time when i try to send POST request via Retrofit. When i sending GET request, it sending correctly. I'm sure that with serverside everyting is ok. What's wrong with my code ?
Here is my request method
#POST("/listing/createListing")
Call<ResponseBody> pushData(#Body RequestBody image);
post implementation modelTask is my model class object and firebaseToken is firebase authentication token. In my model class, I am saving images as a file list.
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new
Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws
IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " +
firebaseToken)
.build();
return chain.proceed(newRequest);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://something.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiEndPoint apiService = retrofit.create(ApiEndPoint.class);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("title", modelTask.getTitle());
builder.addFormDataPart("description", modelTask.getDescription());
builder.addFormDataPart("user_name", "Josim Uddin");
builder.addFormDataPart("user_id", "2133323");
builder.addFormDataPart("price", "30.0");
builder.addFormDataPart("category_name", "Cleaning");
builder.addFormDataPart("category_id", "123");
builder.addFormDataPart("preferred_date",
modelTask.getPreferred_date());
builder.addFormDataPart("preferred_time",
modelTask.getPreferred_time());
builder.addFormDataPart("hasPet", modelTask.getHasPet());
builder.addFormDataPart("budget",
String.valueOf(modelTask.getBudget()));
builder.addFormDataPart("address", modelTask.getAddress());
builder.addFormDataPart("longitude",
String.valueOf(modelTask.getLongitude()));
builder.addFormDataPart("latitude",
String.valueOf(modelTask.getLatitude()));
builder.addFormDataPart("equipment", modelTask.getEquipment());
for (int i = 0; i < modelTask.getImages().size(); i++) {
builder.addFormDataPart("image[]",
modelTask.getImages().get(i).getName(),
RequestBody.create(MediaType.parse("multipart/form-data"),
modelTask.getImages().get(i)));
}
MultipartBody requestBody = builder.build();
Call<ResponseBody> call = apiService.pushData(requestBody);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.d(TAG, "onResponse:" + response.code()+",
"+response.message());
if (response.isSuccessful()) {
try {
Log.d(TAG, "post submitted code:" +
response.code()+"body:"+response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "Unable to submit post to API::
"+t.getMessage());
}
});
Postman test is successful.
Try this
#POST("listing/createListing")
Call<ResponseBody> pushData(#Body RequestBody image);
Remove "/" from the link and add it to the end of Base Url.

Android Retrofit2 error 422 on POST request

I want to make a POST request to a server with retrofit, but I always get error 422.
I just wanna know if I do something wrong or it is the server fault.
Retrofit call:
OkHttpClient.Builder duplicateTimeSessionClient = new kHttpClient.Builder();
duplicateTimeSessionClient.addInterceptor(newInterceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", "Bearer "+sharedPreferences.getString("access_token",""))
.header("Accept", "application/vnd.web_app+json; version=1")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
OkHttpClient client = duplicateTimeSessionClient.build();
final Retrofit duplicateTimeSession = new Retrofit.Builder()
.baseUrl(context.getString(R.string.URL))
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
duplicateService = duplicateTimeSession.create(DuplicateTimeSessionInterface.class);
Call<String> duplicateTimeSessionCall = duplicateService.duplicate(createJSON(pos),"api/time-sessions");
duplicateTimeSessionCall.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.i("time-session post",Integer.toString(response.code()));
}
#Override
public void onFailure(Call<String> call, Throwable t) {}
});
Interface:
public interface DuplicateTimeSessionInterface {
#POST
Call<String>duplicate(#Body JSONObject jsonObject, #Url String url);
}
EDIT:
The same JSON works from the browser or iPhone, and some similar calls work from Android, this one just doesn't want to go through.

How to make a POST with empty body using OKHttp

I'm facing a different Api Service which I have to request using POST but with no body content, I'm sending a image converted to base64, I've been searching about that issue and I found this "solution", which it didn't work :
1 :
RequestBody reqbody = RequestBody.create(null, new byte[0]);
Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0");
2 :
request = new Request.Builder()
.url(BASE_URL + route)
.method("POST", RequestBody.create(null, new byte[0]))
.post(requestBody)
.build();
Even I explicit saying that is a POST method, it keeps send a GET request and not a POST request. Thanks!
My Activity :
public String SendImage(String image64) throws IOException{
//RequestBody reqbody = RequestBody.create(null, new byte[0]);
Request request = new Request.Builder()
.url("http://ap.imagensbrasil.org/api/1/upload/?key=9c9dfe77cd3bdbaa7220c6bbaf7452e7&source=" + image64 + "&format=txt")
.method("POST", RequestBody.create(null, new byte[0]))
.header("Content-Length", "0")
.build();
OkHttpClient Client = client.newBuilder() .readTimeout(25, TimeUnit.SECONDS).build();
Response response = Client.newCall(request).execute();
return response.body().string();
}
It is working on retrofit , so if you continue with Retrofit v2.0 you can use this :
public class Base64EncodeRequestInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder builder = originalRequest.newBuilder();
if (originalRequest.method().equalsIgnoreCase(POST)) {
builder = originalRequest.newBuilder()
.method(originalRequest.method(), encode(originalRequest.body()));
}
return chain.proceed(builder.build());
}
private RequestBody encode(RequestBody body) {
return new RequestBody() {
#Override
public MediaType contentType() {
return body.contentType();
}
#Override
public void writeTo(BufferedSink sink) throws IOException {
Buffer buffer = new Buffer();
body.writeTo(buffer);
byte[] encoded = Base64.encode(buffer.readByteArray(), Base64.DEFAULT);
sink.write(encoded);
buffer.close();
sink.close();
}
};
}
}

how to send body parameter with multipart file upload request in OKhttp

I am trying to upload a file using multipart request in okhttp.
using below code.
public static Boolean uploadFile(String serverURL, File file) {
try {
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/csv"), file))
.addFormDataPart("some-field", "some-value")
.build();
Request request = new Request.Builder()
.url(serverURL)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
// Handle the error
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
// Handle the error
}
// Upload successful
}
});
return true;
} catch (Exception ex) {
// Handle the error
}
return false;
}
which is working file.
My problem is- i also wants to send some key value pair in body parameters but it is creating problem in request.
I am using below code to append key value body parameters in multipart request.
FormBody.Builder formBodyBuilder = new FormBody.Builder();
formBodyBuilder.add("name", "Mac");
requestBody.addPart(formBodyBuilder.build());
but it is creating problem.
Any help will really appreciated. Thanks
I am doing this with Okhttp3 and it works fine:
MediaType MEDIA_TYPE = MediaType.parse(MIME_TYPE);
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type", stringsToPost[0])
...
.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE, file));
you try this
RequestBody formBody = new FormBody.Builder()
.add("grant_type", "")
.add("username", "")
.add("password", "")
.build();
RequestBody requestBodyy = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(
Headers.of("content-type", "form-data; name=\"image\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("content-type", "application/json; charset=utf-8"),
formBody)
.build();

Categories