Custom Async Http Client in Android - java

I use https://github.com/loopj/android-async-http but I think this can be applied to an Async Task (native one)
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
//Some debugging code here
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
//here is the interesting part
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Some debugging code here, show retry dialog, feedback etc.
}
#Override
public void onRetry(int retryNo) {
//Some debugging code here-------
}
});
I use it alot in lots of separate classes. The onStart, onFailure and onRetry are the same everywhere, just copy-paste, just the onSuccess is different.
I want to keep my code as clean as possible and to reuse what I've already written, so my question is, how do I make this custom, in a separate "file", and just reuse it. I need just the "OnSuccess" function. Thank you
---------------------------------------
SOLUTION for GET & POST (Thanks to furkan3ayraktar)
1st file RequestListener
package com.classicharmony.krakenmessages.utils.AsyncHttp;
import org.apache.http.Header;
public interface RequestListener {
public void onSuccess(int statusCode, Header[] headers, byte[] response);
}
2nd file RequestHandler
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
public class RequestHandler {
private static RequestHandler instance;
private AsyncHttpClient client;
private static final boolean SHOW_DEBUG_ALERT_DIALOG = true;
private RequestHandler() {
client = new AsyncHttpClient();
}
public static RequestHandler getInstance() {
if (instance == null) {
instance = new RequestHandler();
}
return instance;
}
public void make_get_Request(final Context context, final String url, final RequestListener listener) {
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
Log.v("▒▒▒▒▒▒▒ GET ", url);
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Log.e("▒▒▒▒▒▒▒ GET FAILED ", url);
Log.e("▒▒▒▒▒▒▒ GET FAILED ", e.getLocalizedMessage());
if (DUtils.isDebuggable(context) && SHOW_DEBUG_ALERT_DIALOG) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("▒▒▒▒▒ ERROR ▒▒▒▒▒");
String error_msg;
if (errorResponse != null) {
try {
error_msg = String.valueOf(new String(errorResponse, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
error_msg = e.getLocalizedMessage();
}
} else {
error_msg = e.getLocalizedMessage();
}
builder.setMessage(context.getClass().getSimpleName() + " -> " + error_msg)
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
#Override
public void onRetry(int retryNo) {
Log.e("▒▒▒▒▒▒▒ RETRYING ", "....." + String.valueOf(retryNo));
}
});
}
public void make_post_Request(final Context context, final StringEntity entity, final String url, final RequestListener listener) {
client.post(context, url, entity, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onStart() {
Log.v("▒▒▒▒▒▒▒ POST ", url);
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Log.e("▒▒▒▒▒▒▒ POST FAILED ", url);
Log.e("▒▒▒▒▒▒▒ POST FAILED ", context.getClass().getSimpleName() + " -> " + e.getLocalizedMessage());
if (DUtils.isDebuggable(context) && SHOW_DEBUG_ALERT_DIALOG) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("▒▒▒▒▒ ERROR ▒▒▒▒▒");
String error_msg;
if (errorResponse != null) {
try {
error_msg = String.valueOf(new String(errorResponse, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
error_msg = e.getLocalizedMessage();
}
} else {
error_msg = e.getLocalizedMessage();
}
builder.setMessage(context.getClass().getSimpleName() + " -> " + error_msg)
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
#Override
public void onRetry(int retryNo) {
Log.e("▒▒▒▒▒▒▒ RETRYING ", "....." + String.valueOf(retryNo));
}
});
}
}
3rd "utility" to show the dialog or not.
public static boolean isDebuggable(Context ctx) {
boolean debuggable = false;
X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
try {
PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
Signature signatures[] = pinfo.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (int i = 0; i < signatures.length; i++) {
ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
if (debuggable)
break;
}
} catch (PackageManager.NameNotFoundException e) {
//debuggable variable will remain false
} catch (CertificateException e) {
//debuggable variable will remain false
}
return debuggable;
}
Example how to call it for POST:
JSONObject jsonParams = new JSONObject();
StringEntity entity;
try {
jsonParams.put("from_user_id", "dan");
jsonParams.put("to_user_id", "vili");
jsonParams.put("message", "hello world");
entity = new StringEntity(jsonParams.toString());
} catch (JSONException e) {
e.printStackTrace();
return;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
RequestHandler handler = RequestHandler.getInstance();
handler.make_post_Request(getActivity(), entity, "http://your_server/api/etc", new RequestListener() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
try {
String server_response = String.valueOf(new String(response, "UTF-8"));
Log.v("Server response",server_response);
} catch (UnsupportedEncodingException e1) {
}
}
});

You could create your own, empty version of AsyncHttpResponseHandler, which doesn't implement the onSuccess method.
public abstract class OWADVLHttpResponseHandler extends AsyncHttpResponseHandler {
#Override
public void onStart() {}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {}
#Override
public void onRetry(int retryNo) {}
}
Your code would then look like:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new OWADVLHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
....
}
});
Obviously, you can fill in some contents in the non-overrided methods in the base class.

First you make an abstract base class that implements the behavior that is common. Something like this:
public abstract class AsyncHttpResponesHandlerBase implements AsyncHttpResponseHandler {
#Override
public void onStart() {
// called before request is started
// Some debugging code here
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Some debugging code here, show retry dialog, feedback etc.
}
#Override
public void onRetry(int retryNo) {
//Some debugging code here-------
}
}
Then per url you inherited from the base class and implement the onSuccess() method to handle the response.
public class GoogleGetHandler extends AsyncHttpResponesHandlerBase {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
// do the Google specific handling
}
}
And you make the HTTP request as follows:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new GoogleGetHandler());
So if you want to make calls to more urls, just keep making new subclasses based off of the base class so you inherit the common failure handling.

Create common request handler and listener. You can also create different request methods like makeRequest for each request you want, and also create different listeners. Here is a simple pattern I mostly use,
public class RequestHandler{
private static RequestHandler instance;
private AsyncHttpClient client;
private RequestHandler(){
client = new AsyncHttpClient();
}
public static RequestHandler getInstance(){
if(instance == null){
instance = new RequestHandler();
}
return instance;
}
// You can add more parameters if you need here.
public void makeRequest(String url, RequestListener listener){
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
//Some debugging code here
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Some debugging code here, show retry dialog, feedback etc.
}
#Override
public void onRetry(int retryNo) {
//Some debugging code here-------
}
});
}
}
public interface RequestListener{
public void onSuccess(int statusCode, Header[] headers, byte[] response);
}
Then use as following in anywhere you want.
RequestHandler handler = RequestHandler.getInstance();
handler.makeRequest("http://www.google.com", new RequestListener(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// do whatever you want here.
}
});

*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.google.code.gson:gson:2.2.4'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
ShowProgress();
}
#Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}
implements LocationListener {
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private String vendorId, vendorName, vendorPhone, vendorImg, vendorDistance, vendorStar, vendorRate, vendorAddress, vendorSummary, vendorOtherService;
LocationManager locationManager;
private FusedLocationProviderClient mFusedLocationProviderClient;
private boolean mLocationPermissionGranted;
private Location mLastKnownLocation;
init()
{
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
#Click
public void lnrCurrentLocation() {
getLocationPermission();
getDeviceLocation();
}
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted)
{
final Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
MarkerOptions markerOptions = new MarkerOptions();
if (task.isSuccessful()) {
mLastKnownLocation = task.getResult();
if(mLastKnownLocation!=null)
{
Double lat = mLastKnownLocation.getLatitude();
Double lng = mLastKnownLocation.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(AddAddressActivity.this, Locale.getDefault());
try {
Log.e("latitude", "inside latitude--" + lat);
addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
edtAddress.setText(address );
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (lat != null && lng != null) {
fastSave.saveString(Constant.CURR_LAT, String.valueOf(mLastKnownLocation.getLatitude()));
fastSave.saveString(Constant.CURR_LON, String.valueOf(mLastKnownLocation.getLongitude()));
} else {
getDeviceLocation();
}
}
}
}
});
}
else {
Log.d("#permision","======== Permision not found =========");
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
"GOOGLE MAP IN ANDROID"
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-maps:11.8.0'
implementation 'com.github.pedroSG94:AutoPermissions:1.0.3'
<meta-data
android:name="#string/permissions_loader_meta_key"
android:value="android.permission.WRITE_EXTERNAL_STORAGE, android.permission.CAMERA,android.permission.ACCESS_FINE_LOCATION,android.permission.ACCESS_COARSE_LOCATION" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
implements OnMapReadyCallback, AutoPermissionsListener {
private GoogleMap mMap;
AutoPermissions.Companion.loadActivityPermissions(DashboardActivity.this, 1);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
AutoPermissions.Companion.parsePermissions(DashboardActivity.this, requestCode, permissions, this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(0.0, 0.0);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onDenied(int i, String[] strings) {
}
#Override
public void onGranted(int i, String[] strings) {
}

-----------------------------------------------------
LATEST Calling Api USing Retrofit
Api Call USING RETROFIT With GET & POST
-----------------------------------------------------
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
implementation "com.android.support:cardview-v7:28.0.0"
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
1] GET API WITH DISPLAY DATA IN RECYCLERVIEW :-
ApiInterface
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface
{
#GET("/photos")
Call<List<RetroPhoto>> getAllPhotos();
}
RestApiClient
mport retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestApiClient {
private static Retrofit retrofit;
private static final String BASE_URL = "https://jsonplaceholder.typicode.com";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private CustomAdapter adapter;
private RecyclerView recyclerView;
ProgressDialog progressDoalog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMessage("Loading....");
progressDoalog.show();
/*Create handle for the RetrofitInstance interface*/
ApiInterface service = RestApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<List<RetroPhoto>> call = service.getAllPhotos();
call.enqueue(new Callback<List<RetroPhoto>>() {
#Override
public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
progressDoalog.dismiss();
generateDataList(response.body());
}
#Override
public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
progressDoalog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<RetroPhoto> photoList) {
recyclerView = findViewById(R.id.customRecyclerView);
adapter = new CustomAdapter(this, photoList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
activity_main
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/customRecyclerView"
android:layout_height="match_parent"
/>
custom_row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/coverImage"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:id="#+id/title"
android:textSize="15dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
RetroPhoto
import com.google.gson.annotations.SerializedName;
public class RetroPhoto {
#SerializedName("albumId")
private Integer albumId;
#SerializedName("id")
private Integer id;
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("thumbnailUrl")
private String thumbnailUrl;
public RetroPhoto(Integer albumId, Integer id, String title, String url, String thumbnailUrl) {
this.albumId = albumId;
this.id = id;
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
public Integer getAlbumId() {
return albumId;
}
public void setAlbumId(Integer albumId) {
this.albumId = albumId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
CustomAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
private List<RetroPhoto> dataList;
private Context context;
public CustomAdapter(Context context,List<RetroPhoto> dataList){
this.context = context;
this.dataList = dataList;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
public final View mView;
TextView txtTitle;
private ImageView coverImage;
CustomViewHolder(View itemView) {
super(itemView);
mView = itemView;
txtTitle = mView.findViewById(R.id.title);
coverImage = mView.findViewById(R.id.coverImage);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.custom_row, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.txtTitle.setText(dataList.get(position).getTitle());
Picasso.get().load(dataList.get(position).getThumbnailUrl()).into(holder.coverImage);
// Picasso.Builder builder = new Picasso.Builder(context);
// builder.downloader(new OkHttp3Downloader(context));
// builder.build().load(dataList.get(position).getThumbnailUrl())
// .placeholder((R.drawable.ic_launcher_background))
// .error(R.drawable.ic_launcher_background)
// .into(holder.coverImage);
}
#Override
public int getItemCount() {
return dataList.size();
}
}
2] POST API WITH LOGIN :-
ApiInterface
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface ApiInterface
{
#FormUrlEncoded
#POST("/login")
// void Login(#FieldMap Map<String, String> map, Callback<Login> callback);
Call<Login> Login(#FieldMap Map<String, String> map);
}
RestApiClient
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestApiClient {
private static Retrofit retrofit;
private static final String BASE_URL = "http://wwwdemo.com/api/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMessage("Loading....");
progressDoalog.show();
Map<String, String> map = new HashMap<>();
map.put("email", edit_email.getText().toString());
map.put("password", edit_password.getText().toString());
map.put("device_type", "android");
map.put("device_token", "dfgdf");
ApiInterface service = RestApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<Login> call = service.Login(map);
call.enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
progressDoalog.dismiss();
if (response.body().getStatus().equals("success")) {
Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_SHORT).show();
Log.d("login", "===== Success ====");
} else {
Toast.makeText(MainActivity.this, "Login Denied!", Toast.LENGTH_SHORT).show();
Log.d("login", "===== Fail ====");
}
}
#Override
public void onFailure (Call < Login > call, Throwable t){
progressDoalog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
Log.d("login", "===== Failure ====");
}
});
}
OTHER TIP
1 pass header is require token only.
#Header("Authorization") String Authorization
2 to pass parameter vie Hasmap
Map<String, String> map = new HashMap<>();
#FieldMap Map<String, String> map
3 image upload with input
#Multipart
#POST("api")
Call<Upload> uploadapi(#Header("Authorization") String token, #Part List<MultipartBody.Part> files, #PartMap Map<String, RequestBody> map);
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("key", RequestBody.create(MediaType.parse("text/plain"), value));
multipart.add(Utility.prepareFilePart(Activity.this, "document_file", picturePath));
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.sine.provider", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
4] void Login(#FieldMap Map<String, String> map, Callback<Login> callback);
RetrofitClient.getInstance().getmRestClient().Login(map, new Callback<Login>() {
#Override
public void success(Login loginResponse, Response response) {
}
}
#Override
public void failure(RetrofitError error) {
}
});
public class RetrofitClient {
private final static String TAG = RetrofitClient.class.getSimpleName();
private static final Object LOCK = new Object();
private static FinalWrapper<RetrofitClient> helperWrapper;
private final RestClient mRestClient;
private RetrofitClient() {
// Rest client without basic authorization
mRestClient = ServiceGenerator.createService(RestClient.class);
}
public static RetrofitClient getInstance() {
FinalWrapper<RetrofitClient> wrapper = helperWrapper;
if (wrapper == null) {
synchronized (LOCK) {
if (helperWrapper == null) {
helperWrapper = new FinalWrapper<>(new RetrofitClient());
}
wrapper = helperWrapper;
}
}
return wrapper.value;
}
public RestClient getmRestClient() {
return mRestClient;
}
ServiceGenerator
public class ServiceGenerator {
private ServiceGenerator() {
}
public static <S> S createService(Class<S> serviceClass) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(Constant.BASE_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(okHttpClient));
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, String username, String password) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(Constant.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(Constant.BASE_URL_USERS)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(okHttpClient));
if (username != null && password != null) {
// concatenate username and password with colon for authentication
final String credentials = username + ":" + password;
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
// create Base64 encodet string
String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", string);
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
public class FinalWrapper<T> {
public final T value;
public FinalWrapper(T value) {
this.value = value;
}
}
5
#GET("/place/autocomplete/json?")
void getplacesLocationList(#Query("input") String str_input,#Query("radius") String radius, #Query("key") String key, Callback<PlacesLocation> callback);
6 pass fist above only post method
interface
#Headers("Content-Type:application/json;charset=UTF-8")
#POST("api/")
Call<Response> get(#Body RequestBody requestBody);
Apiclient
public class ApiClient {
public static final String Tag = "ApiClient";
private static final int CONNECTION_TIMEOUT = 30; //seconds
private static final int READ_TIMEOUT = 20; //seconds
private static final int WRITE_TIMEOUT = 20; //seconds
private static MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
private static MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
private static Retrofit retrofit = null;
private static Gson gson;
public static Retrofit getClient() {
if (retrofit == null) {
OkHttpClient okHttpClient;
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient().newBuilder().connectTimeout
(CONNECTION_TIMEOUT,
TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT,
TimeUnit.SECONDS).addInterceptor(interceptor).build();
} else {
okHttpClient = new OkHttpClient().newBuilder().connectTimeout
(CONNECTION_TIMEOUT,
TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT,
TimeUnit.SECONDS).build();
}
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
}
return retrofit;
}
#NonNull
public static RequestBody makeTextRequestBody(Object stringData) {
return RequestBody.create(MEDIA_TYPE_TEXT, String.valueOf(stringData));
}
#NonNull
public static RequestBody makeGSONRequestBody(Object jsonObject) {
if (gson == null) {
gson = new Gson();
}
return RequestBody.create(MEDIA_TYPE_TEXT, gson.toJson(jsonObject));
}
#NonNull
public static String JSONResponse(Object jsonObject) {
if (gson == null) {
gson = new Gson();
}
String params = gson.toJson(jsonObject);
return params;
}
#NonNull
public static RequestBody makeJSONRequestBody(JSONObject jsonObject) {
String params = jsonObject.toString();
return RequestBody.create(MEDIA_TYPE_TEXT, params);
}
public static JSONObject JSONObject(Object jsonObject) {
if (gson == null) {
gson = new Gson();
}
try {
return new JSONObject(String.valueOf(gson.toJsonTree(jsonObject)
.getAsJsonObject()));
} catch (JSONException e) {
AppLog.handleException(Tag, e);
}
return null;
}
}
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, "");
jsonObject.put(key, "");
jsonObject.put(key, "");
jsonObject.put(key, "");
} catch (JSONException e) {
}
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<Response> aaa = apiInterface.apiname(ApiClient
.makeJSONRequestBody(jsonObject));
aaa.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
}
}
#Override
public void onFailure(Call<Response> call, Throwable t)
{
}
});

Related

Error submitting post request using volley and SpringBoot

I am creating an application to upload a photo to store on the server. However when sending the request via Post appears the following error:
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded' not supported]
I already researched everything, saw some alternatives but none came to solve my problem. I do not know how to come up with a solution.
My API Service:
#RestController
#RequestMapping(value = "/api")
public class Services {
#Autowired
private PacienteRepository pr;
#GetMapping("/pacientes")
public List<Paciente> listaPaciente() {
return pr.findAll();
}
#RequestMapping(value = "/paciente", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Paciente cadastraPaciente(#RequestBody Paciente paciente) {
System.out.println(paciente.foto);
return pr.save(paciente);
}
}
My app:
public class MainActivity extends AppCompatActivity {
public static final String REGISTER_URL = "http://192.168.1.8:8080/api/paciente";
public static final String KEY_IMAGE = "foto";
String foto = "null";
public static final String TAG = "LOG";
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button enviar = (Button) findViewById(R.id.enviar);
enviar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerForms();
}
});
}
public void tirarFoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Bundle bundle = data.getExtras();
if (bundle != null) {
Bitmap img = (Bitmap) bundle.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.JPEG, 100, stream);
foto = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
Toast toast = Toast.makeText(getApplicationContext(), "Foto anexada", Toast.LENGTH_LONG);
toast.show();
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public void registerForms() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
/*if (response.contains("Erro")) {
//progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Erro ao enviar", Toast.LENGTH_LONG).show();
Log.i(TAG, "Lat: " + "Caiu aqui");
} else {*/
//progressDialog.dismiss();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
Toast.makeText(MainActivity.this, "Enviado com sucesso!", Toast.LENGTH_LONG).show();
startActivity(intent);
//}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
Log.i(TAG, "Lat: " + error.getMessage());
Log.i(TAG, "String: " + foto);
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
String requestBody = ""; //The request body goes in here.
try {
return requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> map = new HashMap<String, String>();
map.put("Content-Type","application/x-www-form-urlencoded");
map.put(KEY_IMAGE, "foto1");
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
I am using the following version of volley:
implementation 'com.android.volley:volley:1.1.1'

How to get response from server?

I'm writing a class with requests to rest API (Yandex disk). I use volley, but I do have some problems with getting a response from it. You can check the rest API here.
I use volley and I can get a response in the debugger, but not in my Activity.
Here is my Requests class
class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
Requests (String token, Context context) {
this.token = token;
this.context = context;
}
private void set_response_of_server(String response) {
this.response_of_server = response;
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
/*Request*/
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
/*Request end*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MainActivity where I want my response.
public class MainActivity extends AppCompatActivity {
private final String ID_OF_APP = "Your token of app";
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=token&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_get_code = findViewById(R.id.btn_get_code); // send to get code page (yandex)
btn_get_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(URL_FOR_CODE_QUERY));
startActivity(i);
}
});
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
if(check_token()) {
//Toast.makeText(MainActivity.this, "You are successfully signed in", Toast.LENGTH_SHORT).show();
// TODO change activity
}
else {}
} catch (InterruptedException e) {
e.printStackTrace();
}
//Toast.makeText(MainActivity.this, "Something went wrong. Please, check your connection and try again later", Toast.LENGTH_SHORT).show();
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
private boolean check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
result = request.get_response();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
return !(result.equals("-1"));
}
}
check_token() function at the moment should just make a toast with a response of the server. However, I cannot get the Toast or any response coming back from the server.
You have a Requests class which has the function to call the server API which is Asynchronous. Hence, you will not get the result immediately after calling the request.get_metadata_of_user(); in your check_token() function.
Hence I would like to suggest you modify your Request class like the following.
public class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
private HttpListener listener; // Add a listener to get the callback functionality
Requests (String token, Context context, HttpListener listener) {
this.token = token;
this.context = context;
this.listener = listener; // initialize the listener here
}
private void set_response_of_server(String response) {
this.response_of_server = response;
listener.onResponseReceived(response); // Send the response back to the calling class
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now the HttpListener class might look like the following. Create HttpListener.java and add the following code to create this as an interface.
public interface HttpListener {
public void onResponseReceived();
}
Hence you need to implement this interface in your MainActivity like the following.
public class MainActivity extends AppCompatActivity implements HttpListener {
private final String ID_OF_APP = "Your token of app";
// I fixed this part too. Please change if that is not useful
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=" + SAVED_TOKEN + "&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ... I omitted some code
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
// if(check_token()) {
// The check_token function call is Async. This will not return immediately. Hence you might consider removing this if part. Simply just call the function and listen to the callback function when the response is received
// }
check_token(); // Simply call the function here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
// I changed the return type as this is not returning anything.
private void check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
// You will not get the response immediately here. So omit these codes.
// result = request.get_response();
// Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
// return !(result.equals("-1"));
}
#Override
public void onResponseReceived(String response) {
// Here is your response. Now you can use your response
// and can perform the next action here.
}
}
Please note that, the code is not tested. Please modify as per your requirement. I hope that helps you to understand the problem.

Volley PUT image request

I am trying to make a volley PUT request to upload an image, Since httpEntity is deprecated now, I had to do some other research, I came across these solutions and tried to implement them into my code :
1. https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
2. How to send multipart request using Volley without HttpEntity?
3. Working POST Multipart Request with Volley and without HttpEntity
but still I cannot upload my image. The image I want to upload is either captured from the camera or selected in the gallery, and it is executed onClick.
ProfileSetting.java
public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_setting);
CustomerIcon = (ImageView) findViewById(R.id.CustomerIcon);
confirm_button = (Button) findViewById(R.id.confirm_button);
CustomerIcon.setOnClickListener(new ImageView.OnClickListener(){
public void onClick(View v){
showPickImageDialog();
}
});
confirm_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view) {
//PUT VOLLEY
saveProfileAccount();
}
});
}
private void showPickImageDialog() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
builderSingle.setTitle("Choose Profile Icon");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
ProfileSetting.this,
android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Gallery");
arrayAdapter.add("Camera");
builderSingle.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
case 1:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
}
}
});
builderSingle.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
}
}
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "https://url to put image to";
SharedPreferences sp1=this.getSharedPreferences("FINALTOKEN", Context.MODE_PRIVATE);
final String finalToken = sp1.getString("FINALTOKEN","");
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.PUT, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject result = new JSONObject(resultResponse);
String status = result.getString("status");
String message = result.getString("message");
if (status.equals(Constant.REQUEST_SUCCESS)) {
// tell everybody you have succeed upload image and post strings
Log.i("Messsage", message);
} else {
Log.i("Unexpected", message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers= new HashMap<>();
headers.put("Authorization",finalToken);
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", ImageConverter.getFileDataFromDrawable(getBaseContext(), CustomerIcon.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
}
VolleyMultipartRequest.java and VolleySingleton.java I am using the same class as what my first link has.
My errors are first of all I cannot resolve symbol 'Constant' in the if statement:
if (status.equals(Constant.REQUEST_SUCCESS))
so I tried commenting the statement, after running the code I got the following error:
BasicNetwork.performRequest: Unexpected response code 500 for https://my url
W/System.err: org.json.JSONException: No value for status
I am not sure what is causing my problem,please help, thank you!
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* #param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
//Your response here
}
}
mChoosenFile is your image file
First of all convert your image bitmap to base64 string using the following code:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Then make a PUT Request like the following one and pass the base64 string as a parameter of the request
url = "http://example.com";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("imageString", base64String);
return params;
}
};
queue.add(putRequest);
Refer Android Volley Tutorial if you face any difficulty in implementing volley request.

How to send POST request in JSON using StringRequest

I am trying send post request in Json using StringRequest.I desing Jersey Servlet in java and I created android project in android studio.
I can send json object with Poster Plugin in Chrome but I cant android client.
Please help me.
Jersey Servlet:
#Path("/register")
public class RegisterServlet {
#POST
#Path("/add")
#Consumes(MediaType.APPLICATION_JSON)
public Response addUser(UserDTO user){
if((user.getUsername()=="") || (user.getEmail()=="") || (user.getPassword()=="")){
Logger.getLogger(RegisterServlet.class).info("Name or Email or Password is empty");
return Response.status(200).entity("empty").build();
}
if(Service.getInstance().addUser(user)){
Logger.getLogger(RegisterServlet.class).info("Added User --> username: "+user.getUsername()+"email: "+user.getEmail());
return Response.status(200).entity("add").build();
}else{
Logger.getLogger(RegisterServlet.class).info("Error Add User");
return Response.status(200).entity("error").build();
}
}
}
Android Code ;
private void postUser(final String username,final String email,
final String password,final String dep_name){
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Method.POST,
"http://192.168.56.1:8080/ServerApp/register/add", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", username);
params.put("email", email);
params.put("password", password);
params.put("dep_name", dep_name);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
AppController in Android;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

Volley passing URL

final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest strReq = new StringRequest(Request.Method.GET,
"http://example.com/", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Document document = Jsoup.parse(response);
Elements elementss = document.select("div.category > li");
for (Element element : elements) {
Elements naslov = el.select("div.text > li.headline);
}
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Greška", Toast.LENGTH_SHORT).show();
pDialog.hide();
}
});
AppController.getInstance().addToRequestQueue(strReq);
How could I pass URL parameter, instead of creating new StringRequest everytime i want to parse data, because different URLs have the same HTML structure, could I pass URL parameter when adding StringRequest to RequestQueue, something like:
AppCore.getInstance("http://example.com/").addToRequestQueue(strReq);
And use the same StringRequest several times, but with different URLs?
Also, here's my AppCore.java:
package app.android.volley;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class AppCore extends Application {
public static final String TAG = AppCore.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static AppCore mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppCore getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Basically what I'm trying to do is using one StringRequest multiple times, but with different URLs.
Thanks in advance.
You can try the following way (of course, you can replace JSONArray request by JSONObject request or String request):
VolleyResponseListener listener = new VolleyResponseListener() {
#Override
public void onError(String message) {
// do something...
}
#Override
public void onResponse(Object response) {
// do something...
}
};
makeJsonArrayRequest(context, Request.Method.POST, url, requestBody, listener);
Body of makeJsonArrayRequest can be as the following:
public void makeJsonArrayRequest(Context context, int method, String url, String requestBody, final VolleyResponseListener listener) {
JSONObject jsonRequest = null;
try {
...
if (requestBody != null) {
jsonRequest = new JSONObject(requestBody);
}
...
} catch (JSONException e) {
e.printStackTrace();
}
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
listener.onResponse(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
});
// Access the RequestQueue through singleton class.
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}
VolleyResponseListener interface as the following:
public interface VolleyResponseListener {
void onError(String message);
void onResponse(Object response);
}

Categories

Resources