In my application i need to send an image and array of phone numbers and some unique values to server using retrofit. Here is the code that i have been used, the following code is working if i have removed image from request.
#FormUrlEncoded
#POST("/groups")
#Headers("Accept:application/json")
void createGroupRequest(#Header("mobile-number") String mPhone, #Header("uid") String imei,#Field("group[identification_name]") String jid, #Field("group[name]") String mName,#Field("group[mobile_numbers][]") String[] mMemberNos, Callback<RetrofitResponse> response);
Now i need to send an image data in this request, but how it possible to use both FormUrlEncoded and a multipart data in same request...? is there any other approach in Retrofit..?
Please check my code hope it will help you
private RestAdapter adapter;
private ApiListener apis;
adapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(BASE_URL).build();
apis = adapter.create(ApiListener.class);
TypedString userName = new TypedString("userName");
TypedString name = new TypedString("name");
TypedString emailAddress = new TypedString("emailAddress");
TypedString password = new TypedString("password");
File photoFile = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+"Koala.jpg");
TypedFile photoTypedFile = new TypedFile("image/*", photoFile);
apis.registerUser(userName,name,emailAddress,password,photoTypedFile, new Callback<BaseResponseVo>()
{
#Override
public void failure(RetrofitError arg0)
{
progress.setVisibility(View.INVISIBLE);
}
#Override
public void success(BaseResponseVo arg0, Response arg1)
{
progress.setVisibility(View.INVISIBLE);
}
});
public interface ApiListener
{
#Multipart
#POST("/user/add")
public void registerUser(#Part("userName") TypedString username,#Part("name") TypedString name,#Part("emailAddress") TypedString email,#Part("password") TypedString password,#Part("userPhotoURL") TypedFile photo,Callback<BaseResponseVo> response);
}
Related
i am able to upload image using postman :
but when i tried using multi-part entity using retrofit i am not able to upload that it tell file is not find in server below is my code:
public void visitrecord_existingtask(int userId, String companyId, String taskId, String actionTaken, String timeSpend, double lat, double longi, ArrayList<String> filePaths) {
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("userid", String.valueOf(userId));
builder.addFormDataPart("companyid", companyId);
builder.addFormDataPart("taskid", taskId);
builder.addFormDataPart("task_actiontaken", actionTaken);
builder.addFormDataPart("timespent", timeSpend);
builder.addFormDataPart("latitude", String.valueOf(lat));
builder.addFormDataPart("longitude", String.valueOf(longi));
for (int i = 0; i < filePaths.size(); i++) {
File file = new File(filePaths.get(i));
builder.addFormDataPart("files", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
}
MultipartBody requestBody = builder.build();
Call<VisitrecordExistingtask> call = webAPIInterface.visitrecordExistingtask(requestBody);
call.enqueue(new Callback<VisitrecordExistingtask>() {
#Override
public void onResponse(Call<VisitrecordExistingtask> call, Response<VisitrecordExistingtask> response) {
visitrecordlistner.showLoginResult(response.code(), response.body());
}
#Override
public void onFailure(Call<VisitrecordExistingtask> call, Throwable t) {
visitrecordlistner.showError(t);
}
});
}
this is my code which i am using file upload to server i have to send soem parameter plus image file to server but its not able to find image in server can any one please suggest me what i am doing wrong .
I'm novice on using Retrofit, I want to post data as an json data with object format to server and get response from that, I tested my restful url with fake data and that work fine without any problem, but when i post data from android i get null. what i want to do? i want to post data to server and get response with this format:
public class UserLoginInformation {
private String username;
private String userUniqueId;
}
My interface:
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body Object data);
}
post data:
private void joinUserToApplication(String data) {
AlachiqRestFullProvider signalProvider = new AlachiqRestFullProvider();
SignalRetrofitServiceProviders signalRetrofitServiceProviders = signalProvider.getServices();
Call<List<UserLoginInformation>> call = signalRetrofitServiceProviders.joinUserToApplication(data);
call.enqueue(new Callback<List<UserLoginInformation>>() {
#Override
public void onResponse(Call<List<UserLoginInformation>> call, Response<List<UserLoginInformation>> response) {
List<UserLoginInformation> result = response.body();
final String r = new Gson().toJson(result);
}
#Override
public void onFailure(Call<List<UserLoginInformation>> call, Throwable t) {
t.printStackTrace();
Log.e("onFailure ", t.getMessage());
}
});
}
RestFull provider:
public class AlachiqRestFullProvider {
private SignalRetrofitServiceProviders signalRetrofitServiceProviders;
public AlachiqRestFullProvider() {
OkHttpClient httpClient = new OkHttpClient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ClientSettings.ALACHIQ_WEB_BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
signalRetrofitServiceProviders = retrofit.create(SignalRetrofitServiceProviders.class);
}
public SignalRetrofitServiceProviders getServices() {
return signalRetrofitServiceProviders;
}
}
data for post:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("mobileNumber", mobileNumber);
jsonObject.put("userUniqueId", uuid);
jsonObject.put("userPhoneNumbers", phoneContacts);
startService(
new Intent(context, AlachiqRestFullWebServiceProvider.class)
.putExtra("request_type", "joinUserToApplication")
.putExtra("data", jsonObject.toString()));
} catch (JSONException e) {
e.printStackTrace();
}
server response data like with this format:
{"username":"mahdi","userUniqueId":"fwcrwcrwr23234c24"}
server side application to get data is:
Route.post('joinUserToApplication', function *(request, response) {
console.log(request._raw);
response.send({username: "mahdi", userUniqueId: "fwcrwcrwr23234c24"});
});
The POST body that is being serialized is a generic Object.
Create a POJO with the fields that you require and use a deserializer that retrofit understands
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body UserLoginInformation data);
}
Please note the parameter of the function is not changed to UserLoginInformation
http://square.github.io/retrofit/#restadapter-configuration
I want to fetch json files for different users according to their User_ID, but currently this code is showing empty recyclerview
Retrofit File
public void loadJSONClaim() {
Retrofit retrofitclaim = new Retrofit.Builder()
.baseUrl("http://ec2-54-191-118-200.us-west-2.compute.amazonaws.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterfaceClaim requestclaim = retrofitclaim.create(RequestInterfaceClaim.class);
String User_ID = 5;
Call<JSONResponseClaim> call = requestclaim.getJSONClaim(User_ID);
call.enqueue(new Callback<JSONResponseClaim>() {
#Override
public void onResponse(Call<JSONResponseClaim> call, Response<JSONResponseClaim> responseclaim) {
JSONResponseClaim jsonResponseClaim = responseclaim.body();
dataclaim = new ArrayList<>(Arrays.asList(jsonResponseClaim.getAndroidClaim()));
adapterclaim = new DataAdapterClaim(dataclaim);
}
RequestInterFaceClaim
public interface RequestInterfaceClaim {
#GET("claim.php") // we want to access claim.php?User_ID=5
Call<JSONResponseClaim> getJSONClaim(#Query("User_ID") String User_ID);
}
I'm trying to get data from http://www.gibdd.ru/proxy/check/fines/2.0/client.php, but server responds that captcha is incorrect or expired. In advanced rest client into chrome request work's perfect. My alghoritm to getting data is:
Get session from http://www.gibdd.ru/proxy/check/getSession.php
Get captcha with session id http://www.gibdd.ru/proxy/check/getCaptcha.php?PHPSESSID=te67jgdiv53v956fcv8rk9mg81
And then send form data to http://www.gibdd.ru/proxy/check/fines/2.0/client.php
I think my problem with cookies, i set cookies = sessionId, like rest client, but something gone wrong
UPD: I'm using retrofit to server requests
That API class
private static final String URL= "http://www.gibdd.ru";
private static RestAdapter restAdapter;
public interface IGibdd {
#GET("/proxy/check/getSession.php")
void getSession(Callback<Session> callback);;
#FormUrlEncoded
#POST("/proxy/check/fines/2.0/client.php")
void getFines(#Field("regnum") String regnum,
#Field("regreg") String regreg,
#Field("stsnum") String stsnum,
#Field("req") String reqfines,
#Field("captchaWord") String captchaWord,
Callback<Answer> callback);
}
This method requesting captcha, after getting session id
private void getCaptcha() {
final API.IGibdd iGibdd = API.getRestAdapter(this).create(API.IGibdd.class);
iGibdd.getSession(new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
if (response.getStatus() != 200) {
getCaptcha();
} else {
String cookie = API.loadCookies(CheckFinesActivity.this);
url = getString(R.string.captcha_url) + cookie + "&" + new Date().getTime();
HashMap<String, String> map = new HashMap<String, String>();
map.put("Cookie", cookie);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.extraForDownloader(map)
.build();
ImageLoaderConfiguration conf = new ImageLoaderConfiguration.Builder(CheckFinesActivity.this)
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(conf);
imageLoader.displayImage(url, mCaptchaImage);
}
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
And then, after entering captcha code, i call this method
String reqfines = "fines:" + mCarNumber.getText().toString() + ":" + mCarRegion.getText().toString() + ":" + mDocNumber.getText().toString();
iGibdd.getFines(mCarNumber.getText().toString(),
mCarRegion.getText().toString(),
mDocNumber.getText().toString(),
reqfines,
mCaptcha.getText().toString(),
new Callback<Answer>() {
#Override
public void success(Answer s, Response response) {
Toast.makeText(CheckFinesActivity.this, "Success", Toast.LENGTH_LONG).show();
API.clearSP(CheckFinesActivity.this);
getCaptcha();
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(CheckFinesActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
}
});
UPD2:
Problem is solved. I recreated OkHttp client for a new request and it clears current session
I want to send a photo from local android gallery to the server http Tomcat. For the communication I'm using retrofit. I've established the connection between device and server, and the programme get into servers function but all objects in params are null.
That's the device function declaration on the client side:
#Multipart
#POST("/monument/photo/upload")
void addMonumentPhoto(#Part("MonumentID") Integer monumentId,
#Part("name") String name,
#Part("subscript") String subscript,
#Part("photo") TypedFile photo,
Callback<Photo> callback);
... and that's how I call it:
photo = _resizePhoto(new File(monument.getUriZdjecie()));
typedFile = new TypedFile("multipart/mixed", photo);
//long bytes = photo.length();
if (photo.exists()) {
MonumentsUtil.getApi().addMonumentPhoto(monument.getIdZabytek(),
"podpis",
"Main photo",
typedFile,
new Callback<Photo>() {
#Override
public void success(Photo aPhoto, Response response) {
monument.setUriZdjecie(aPhoto.getUri());
MonumentsUtil.getApi().addMonument(monument.getNazwa(),
monument.getOpis(),
monument.getDataPowstania(),
monument.getWojewodztwo(),
monument.getUriZdjecie(),
monument.getMiejscowosc(),
monument.getKodPocztowy(),
monument.getUlica(),
monument.getNrDomu(),
monument.getNrLokalu(),
monument.getKategoria(),
monument.getLatitude(),
monument.getLongitude(),
new MonumentsCallback());
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, retrofitError.getMessage());
}
});
}
and the server's method:
#RequestMapping(value = "/monument/photo/upload")
public
#ResponseBody
Photo requestMonumentPhotoAdd(#RequestParam(value = "MonumentID", required = false) Integer monumentId,
#RequestParam(value = "name", required = false) String name,
#RequestParam(value = "subscript", required = false) String subscript,
#RequestParam(value = "photo", required = false) MultipartFile file,
HttpServletRequest request) {
Photo photo = new Photo();
if (monumentId != null)
photo.setIdZabytek(monumentId);
photo.setUri(URL + "/images/" + name);
photo.setPodpis(subscript);
photo = monumentsRepo.addPhoto(photo);
String filePath = "D:\\Projects\\Images\\" + monumentId + "_" + photo.getIdZjecia();
if (file != null) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filePath)));
stream.write(bytes);
stream.close();
photo.setUri(filePath);
monumentsRepo.updatePhoto(photo);
return photo;
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
else {
return null;
}
}
Can anybody help me and explain why all objects after geting into the servers method are null?
Maybe method is wrogly writen or the mime field of TypedFile is wrogly chosen but I read that the "multipart/mixed" mime type is for messages with various types of object included in message. I don't have any idea so any advice will be helpful.
Try when creating your TypedFile object to use "image/*" as your mime type. For that "part" it is of that specific type. The "mixed" is likely for the submit as a whole, not the single part that is the file.
typedFile = new TypedFile("image/*", photo);
I also had the similar problems and after few hours trying I finally built image uploading functionality to remote server.
To upload image you need to create the API properly and also need to pass the image properly.
This should work fine for you:
In Retrofit client you need to set up the image as followed:
String photoName = "20150219_222813.jpg";
File photo = new File(photoName );
TypedFile typedImage = new TypedFile("application/octet-stream", photo);
RetrofitClient.uploadImage(typedImage, new retrofit.Callback<Photo>() {
#Override
public void success(Photo photo, Response response) {
Log.d("SUCCESS ", "SUCCESS RETURN " + response);
}
#Override
public void failure(RetrofitError error) {
}
});
API SET UP:
#Multipart
#POST("/")
void uploadImage(#Part("file") TypedFile file, Callback<Photo> callback);
Remote Server Side PHP Code to handle the image:
........
$pic = 'uploaded_images/' . $imagename . '.jpg';
if (!move_uploaded_file($_FILES['file']['tmp_name'], $pic)) {
echo "posted";
}
.........
If it helps any one please recognize me..thanks a lot..