How to call Restful web service in android
And I got the answer finally and working fine for me... I have posted the working code below.
public class LoginActivity extends Activity
{
String Returned;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://Your url here/");
StringEntity str = new StringEntity("Your xml code");
str.setContentType("application/xml; charset=utf-8");
str.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/xml; charset=utf-8"));
post.setEntity(str);
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
Returned = EntityUtils.toString(entity);
Toast.makeText(this, Returned, Toast.LENGTH_LONG).show();
} catch ( IOException ioe ) {
ioe.printStackTrace();
}
}
}
thanks a lot for all your responses.
How to call a Web Services using Android
Try using some Libraries such as Retrofit, Volley, Loopj etc for Asynchrous GET or POST HTTP Requests.
For Implementing dynamic image from url or file path use Piccasso or Glide Library.
Here are some examples and documentation on these libraries
Loopj
- Loopj official Documentation and Example
Retrofit
- Retrofit official Documentation By SquareUp
- Retrofit Tutorial from JournelDev
Volley
- Volley official Documenation By Android Developers
- Volley tutorial from Journeldev
DYNAMIC IMAGE HANDLING
Picasso
Android Picasso Library
Glide
Glide Library for Android
Hope these may help you
Example with Retrofit
build.gradle(app)
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
MainFragment
public class MainFragment extends Fragment {
public static final String PREFS = "prefFile";
final String LOG = "MainFragment";
private ArrayList<Product> productList;
private ListView lv;
FunDapter adapter;
private ApiInterface apiInterface;
View view;
public MainFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lv = (ListView) view.findViewById(R.id.lvProduct);
apiInterface = ApiClient.getRetrofitApiClient().create(ApiInterface.class);
productList = new ArrayList<Product>();
adapter= new FunDapter (getContext(), 0, productList);
lv.setAdapter(adapter);
getProduct();
}
private void getProduct() {
Call<List<Product>> call = apiInterface.getProducts();
call.enqueue(new Callback<List<Product>>() {
@Override
public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
List<Product> products= response.body();
Log.d("TEST", "onResponse: "+response.body().size());
if(products.size()>0){
productList.addAll(products);
}
adapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<List<Product>> call, Throwable t) {
}
});
}
}
ApiClient
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by android on 3/10/17.
*/
class ApiClient {
public static final String BASE_URL = "http://10.0.2.2:8080/WebService/rest/";
public static Retrofit retrofit = null;
public static Retrofit getRetrofitApiClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
ApiInterface
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface ApiInterface {
@GET("get/products")
Call<List<Product>> getProducts();
}
Products
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
class Product {
@SerializedName("name")
@Expose
private String name;
@SerializedName("ram")
@Expose
private String ram;
@SerializedName("price")
@Expose
private String price;
@SerializedName("pic")
@Expose
private String pic;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRam() {
return ram;
}
public void setRam(String ram) {
this.ram = ram;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
FunDapter
class FunDapter extends ArrayAdapter<Product> {
private Context context;
private ArrayList<Product> objects;
private static LayoutInflater inflater = null;
public FunDapter(@NonNull Context context, int resource, @NonNull ArrayList<Product> objects) {
super(context, resource, objects);
try {
this.context = context;
this.objects = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
}
}
public int getCount() {
return objects.size();
}
public Product getItem(Product position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView display_number;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.singlerow_mylistview, null);
holder = new ViewHolder();
holder.display_name = (TextView) vi.findViewById(R.id.title_listview);
holder.display_number = (TextView) vi.findViewById(R.id.subtitle_listview);
holder.image = (ImageView) vi.findViewById(R.id.icon_listview);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.display_name.setText(objects.get(position).getName());
holder.display_number.setText(objects.get(position).getPrice());
Picasso.with(context)
.load(objects.get(position).getPic())
.resize(50, 50)
.centerCrop()
.into(holder.image);
} catch (Exception e) {
}
return vi;
}
}
Dont forget to add <uses-permission android:name="android.permission.INTERNET" />
in Manifest
consuming rest web service in android
I changed send PostRequest with this code: //SEND Get data reques HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET");& it works
Calling a RESTful Web Service using FutureTask
Future + HttpClient = AsyncHttpClient
If AsyncHttpClient.onSuccess() or AsyncHttpClient.onFailure() is called, it means the thread is finished, or it's still running(blocked).
==EDIT==
Ok, an example here. Please read more about FutureTask and Executor in java doc.
FutureTask<HttpResult> future = new FutureTask<HttpResult>(new Callable<HttpResult>() {
// GET A HTTP RESULT IN ANOTHER THREAD
@Override
public HttpResult call() throws Exception {
HttpClient httpClient =new HttpClient();
//set url, http method and params
HttpResult result = httpClient.getResult(); // sync request, it costs a long time.
return result;
}
}){
// FutureTask.DONE() WILL BE CALLED ASYNCHRONOUSLY
@Override
protected void done() {
try {
HttpResult result=get();
//read the result
} catch (InterruptedException e) {
logger.error("", e);
} catch (ExecutionException e) {
logger.error("", e);
}
}
};
How do I call REST API from an android app?
- If you want to integrate Retrofit (all steps defined here):
Goto my blog : retrofit with kotlin
- Please use android-async-http library.
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/
http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
Locally call RESTful Web Service generated by NetBeans IDE from Android?
Your HTTP URL is "http://localhost:8080/..." i.e. it expects to reach a server running on the Android device. If your IDE/service is running on your workstation then:
- If you're running the app on the Genymotion emulator use 10.0.3.2 instead of localhost
- If you're running the app on the SDK emulator use 10.0.2.2 instead of localhost
- If you're running the app on a real device then substitute the IP
address of your workstation and make sure the device and workstation are on the same network.
References:
- How to access localhost from a Genymotion android emulator
- Emulator Networking
how to call RESTful web service from android?
Do you use basic authentication? if so: use this.
if (username != null && password != null) {
client.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new UsernamePasswordCredentials(username, password));
}
or you can add those in a header as setHeader("Authentication", "Basic "+Base64EncodedString(username,pass);
What you are doing is using Proxy authentication. why?
this article may also be helpful somehow:
link
also the -u stands for the ntlm authorization so maybe look into that too. there were some topics where it said it is not supported on android or something but i am sure if you need it you can make a workaround.
Related Topics
How to Solve the "Double-Checked Locking Is Broken" Declaration in Java
Encoding Url Query Parameters in Java
Variable Length (Dynamic) Arrays in Java
What to Learn for Making Java Web Applications in Java Ee 6
What Is Difference Between Collection.Stream().Foreach() and Collection.Foreach()
Sort Arrays of Primitive Types in Descending Order
Singleton Class with Several Different Classloaders
Jtable, Rowfilter and Rowfilter.Entry
Absolute Positioning Graphic JPAnel Inside Jframe Blocked by Blank Sections
Jersey Rest Web Service with Activemq Middleware Integration
Background Timer Task in Jsp/Servlet Web Application
How to Use an Arraylist as a Prepared Statement Parameter
Null Check Chain VS Catching Nullpointerexception
Spinner Onitemselected() Executes Inappropriately
How One Interface Can Be Used for Different Background Android Tasks