User can get image from camera and gallery aslo user can crop image and setting in view working good.but after that i want to update it's profile with it's other data like "Name" ,"Number" etc.
by postman image is uploading successfully.
I tried multipart, way sending as file and also try to send as a string but not getting successful or Failure response.i don't know what I m doing wrong. I m new in android please help if you can.
Response and Get Structure
{
"id": 7,
"profile_image": " ImageUrl will come here",
"firstname": "Hamza",
"lastname": "Ali",
"email": "hamzaregardless333#gmail.com",
"contact": "123455666",
"gender": "Male",
"location": "lahore"
}
I don't know where you made a mistake because you didn't share your code.
I'm uploading image like below. Maybe it can help you.
Your Service
public interface YourService {
#Multipart
#POST("api/exampleImageUpload")
Call<YourResponse> uploadImage(
#Part MultipartBody.Part image
);
}
Uploading Image
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://backendapi.com/")
.build();
File file = new File(imagePath);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("paramName","imageName",RequestBody.create(MediaType.parse("multipart/form-data"), file));
YourService iys = retrofit.create(YourService.class);
Call<YourResponse> uploadCall = iys.uploadImage(filePart);
uploadCall.enqueue(new Callback<YourResponse>() {
#Override
public void onResponse(Call<YourResponse> call, Response<YourResponse> response) {
}
#Override
public void onFailure(Call<YourResponse> call, Throwable t) {
}
});
Related
I am making a app using google Fact Check API and and the response json is like this
{
"claims": [
{
"text": "“President El-Sisi confirmed Egypt's unwavering strategic position on Libya, which aimed at restoring stability in the country, preserving its national institutions, and preventing further deterioration in Libya’s security situation via curbing illegal foreign interference in the Libyan issue.”",
"claimant": "Abdel-Fattah al-Sisi",
"claimDate": "2020-07-24T00:00:00Z",
"claimReview": [
{
"publisher": {
"name": "POLYGRAPH.info",
"site": "polygraph.info"
},
"url": "https://www.polygraph.info/a/egypt-libya-sisi-intervention/30745850.html",
"title": "Egypt's al-Sisi Told Trump Foreign Interference in Libya is Bad – Just as his Parliament Authorized him to Intervene",
"reviewDate": "2020-07-24T00:00:00Z",
"textualRating": "Misleading",
"languageCode": "en"
}
]
}
],
"nextPageToken": "CAE"
}
I want to know how can i get the urls image and display it like this
image
I can't seem to figure out how to get the image as in the JSON there is only url of the webpage.
Edit:-
Here is the code in which i am using GSON to store the values
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("response",response.toString());
Search search = gson.fromJson(response.toString(),Search.class);
Log.i("response",search.toString());
textView.setText("Claim:- "+search.claims.get(0).text+"\nFactual Rating:-"+search.claims.get(0).claimReview.get(0).textualRating);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("response",error.toString());// TODO: Handle error
}
});
If you know the exact website you can use a web scraper. Look how you can do it here.
I am trying to upload audio file to Speaker Recognition from retrofit but getting the Invalid Audio Error:
please find the code below:
public void createEnrollment(String verficationId,String file) throws IOException {
RequestBody videoBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("audio", file, videoBody);
ApiInterface service = RetrofitClientInstance.getRetrofitInstance().create(ApiInterface.class);
Call<List<EnrolmentResult>> call = service.postAudioAndGetResponse(API_KEY,verficationId,vFile);
call.enqueue(new Callback<List<EnrolmentResult>>() {
#Override
public void onResponse(Call<List<EnrolmentResult>> call, Response<List<EnrolmentResult>> response) {
Log.d("Result", response.body().toString());
}
#Override
public void onFailure(Call<List<EnrolmentResult>> call, Throwable t) {
//progressDoalog.dismiss();
Log.d("Error", t.getMessage());
}
});
}
public interface ApiInterface {
#Multipart
#POST("identificationProfiles/{verificationProfileId}/enroll")
Call <List<EnrolmentResult>> postAudioAndGetResponse(#Header("Ocp-Apim-Subscription-Key") String keyValue,
#Path("verificationProfileId") String id,
#Part MultipartBody.Part file
);
}
Audio is .wav format and converted to below format:
Container WAV
Encoding PCM
Rate 16K
Sample Format 16 bit
Channels Mono
When i send the same from Post Man i am getting the 202 response as Success
Have you tried using application/json for the media type? ... looks like all calls expect this , even though we are sending binary
I try to upload an image from an Android App to a Django server using Retrofit 2 and OkHttp3.
For that, I used to create a RequestBody instance using the following lines:
RequestBody requestImageFile =
// NOW this call is DEPRECATED
RequestBody.create(
MediaType.parse("image/*"),
// a File instance created via the path string to the image
imageFile
);
I used the previous instance in the next method call as argument:
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part image = MultipartBody.Part.createFormData("image", imageFile.getName(), requestImageFile);
Finally, I fired up the Retrofit interface to do the rest:
// finally, execute the request
Call<ResponseBody> call = service.upload(image);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
Some months ago, Android Studio did not told me that create() was deprecated. When I open the project now, it tells me that create() is deprecated. Does somebody know how to fix it ?
Just swap the parameters from
RequestBody.create(MediaType.parse("image/*"), imageFile);
to
RequestBody.create(imageFile, MediaType.parse("image/*"));
You can use the Kotlin extensions as well.
val requestImageFile = imageFile.asRequestBody("image/*".toMediaTypeOrNull())
Here is how to do it easily with kotlin extension functions from okhttp like:
toRequestBody():
change from :
val requestImageFile = RequestBody.create(
MediaType.parse("image/*"),
imageFile
);
to this:
val requestImageFile = imageFile.toRequestBody(MediaType.parse("image/*"))
'
more info here: https://square.github.io/okhttp/upgrading_to_okhttp_4/
You can change from:
RequestBody.create(MediaType.parse("image/*"), imageFile);
to:
RequestBody.Companion.create(imageFile, MediaType.parse("image/*"))
I'm trying to upload an image from Android Studio to Laravel server using Retrofit2 Multipart encoding, but i keep getting "500 Internal Server Error", which means something is going wrong server-side probably, but i can't pin what it is.
this is my interface call (Android Studio):
#Multipart
#POST("public/imagem")
Call<ResponseBody> uploadImagem(#Part MultipartBody.Part part,
#Part("name") RequestBody name,
#Part("animal_id") long animal_id,
#Part("ativo") int ativo);
this is the request (Android Studio):
//Create a file object using file path
File file = new File(filePath);
// Create a request body with file and image media type
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
// Create MultipartBody.Part using file request-body,file name and part name
MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);
//Create request body with text description and text media type
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "image-type");
WebService.getInstance().getService().uploadImagem(part, name, animal_id, 1).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
//THIS IS WHERE I WANT TO GET
} else {
//THIS IS WHERE IM GETTING AT EVERYTIME
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
this is my route (Laravel):
Route::post('imagem','ImagemController#createImagem');
this is the "createImagem" function inside "ImagemController" (Laravel):
public function createImagem(Request $request){
$destinationPath = url('/midia'); //i have a "midia" folder inside "public" folder
$image = $request->file('part');
$name = $request->input('name');
$image->move($destinationPath, $name);
$dbPath = $destinationPath. '/'.$name;
$imagem = new Imagem();
$imagem->animal_id = $request->input('animal_id');
$imagem->img_url = $dbPath;
$imagem->ativo = $request->input('ativo');
$imagem->save();
return response()->json($imagem);
}
and these are the attributes inside "Imagem" table and their types:
but i'm getting 500 Internal Server Error, so probably something server-side isn't according to what would be right logically, can you help me find what is wrong in my code?
ps. I do have other requests to this server that are fully functional, but all of them are just fields, while this has a file, which needs Multipart encoding, unlike the others.
EDIT:
This is the server error log:
[2019-06-11 21:21:03] local.ERROR: Call to a member function move() on null {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function move() on null at /.../Controllers/ImagemController.php:28)
So it seems i am unable to get file with
$image = $request->file('part');
I think the error could be because path must to be a path and not an url:
$destinationPath = url('/midia');
If you want to move the file to public folder, you have to use public_path() for the path:
$image = $request->file('part');
$destinationPath = 'midia';
$name = $request->input('name') .'.'. $image->getClientOriginalExtension();
$image->move(public_path($destinationPath), $name);
If you want to avoid the error and not waste server resources when there is no image in the request, add a validation at the start of your function:
public function createImagem(Request $request){
$this->validate($request, [
'part' => 'required|image|max:2048',
// other fields validations
]);
// the createImagem logic here
}
if the validation fails, you will not try to move the file and will not query DB either, then the proper error response will automatically be sent back to the client where you can handle it.
try this code hope its helpfull for you.
#Multipart
#POST("public/imagem")
Call<ResponseBody> uploadImagem(#Part MultipartBody.Part part);
if you are using key part
$image = $request->file('part');
also use that key "part" in java code
Uri uri1 = Uri.parse(event_image);
File file = new File(uri1.getPath());
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part image = MultipartBody.Part.createFormData("part", file.getName(), reqFile);
mService.addEvent(image).enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
}
});
My requirement is to store credit card details in Paypal vault using Android.
I followed these link
https://github.com/paypal/PayPal-Java-SDK
https://github.com/paypal/PayPal-Android-SDK
https://developer.paypal.com/docs/integration/direct/rest-vault-overview/
there is no mention on how to vault a credit using Android sdk. I think it can be done using their Rest API. How do I achieve this in Android?
You can store credit card in paypal using vault api Follow this steps
Step 1: Generate Access Token By OAuth Token Request
Try in postman
Url :- https://api.sandbox.paypal.com/v1/oauth2/token
Headers :- (Key,Value)
1.(Accept , application/json)
2.(Accept-Language , en_US)
3.(Content-Type , application/x-www-form-urlencoded)
4.(Authorization , Basic<Space>(here your code generated by postman))
Note :- Generate a Basic Auth in post man by select authorization tab ==> Basic Auth and enter paypal Client secret and Client id.
Body :- (Key,Value)
1.(grant_type,client_credentials)
Note :- Select x-www-form-urlencoded in body tab in postman
Step 2: Store credit card using valut api
Try in postman
Url :- https://api.sandbox.paypal.com/v1/vault/credit-cards
Headers :- (Key,Value)
1.(Accept , application/json)
2.(Accept-Language , en_US)
3.(Content-Type , application/x-www-form-urlencoded)
4.(Authorization , Bearer(your Access Token))
Body : (Json)
{
"payer_id": "user12345",
"type": "visa",
"number": "4111111111111111",
"expire_month": "11",
"expire_year": "2018",
"first_name": "Joe",
"last_name": "Shopper",
"billing_address": {
"line1": "52 N Main ST",
"city": "Johnstown",
"state": "OH",
"postal_code": "43210",
"country_code": "US"
}
}
Note :- Select raw tab in body in postman.
Thanks to vishal for his help. I was able to solve this using retrofit (adding headers statically).
1. First get the value of your authorization header:
String clientId = "your client id";
String clientSecret = "your client secret";
String credentials = clientId + ":" + clientSecret;
String basic =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
Log.e("Authorization",basic);
Copy this value from log, it will be used later in our solution.
2. Make the response model according to this json:
{
"scope":"https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.*",
"access_token":"Access-Token",
"token_type":"Bearer",
"app_id":"APP-6XR95014SS315863X",
"expires_in":28800
}
3. Make retorfit call method as this:
#Headers({
"Accept: application/json",
"Accept-Language : en_US",
"Content-Type : application/x-www-form-urlencoded",
"Authorization:your basic string value here"
})
#POST("https://api.sandbox.paypal.com/v1/oauth2/token/")
Call<AuthenticationTokenModel> getAuthentionToken(#Query("grant_type") String grant_type);
4. Finally make the call as:
ApiInterface apiInterface= ApiClient.getClient().create(ApiInterface.class);
apiInterface.getAuthentionToken("client_credentials").enqueue(new Callback<AuthenticationTokenModel>() {
#Override
public void onResponse(Call<AuthenticationTokenModel> call, Response<AuthenticationTokenModel> response) {
Log.e("response",response.body().getAccess_token());
}
#Override
public void onFailure(Call<AuthenticationTokenModel> call, Throwable t) {
Log.e("response",t.getMessage());
}
});
Thanks.
Edited:
You can also add dynamic headers to requests in Retrofit 2.
Follow this:
https://futurestud.io/tutorials/retrofit-add-custom-request-header