代码之家  ›  专栏  ›  技术社区  ›  user9569492

如何使用Android调用Web服务

  •  1
  • user9569492  · 技术社区  · 8 年前

    我是Android应用程序开发的新手。我正在开发一个购物车应用程序。我正在尝试使用android调用GET方法中的web服务。但我该怎么做呢?我试过的就在这里。但这给了我一个错误 PostResponseAsyncTask: 405 Method not allowed .如何修复?有人能帮我吗?提前谢谢。

    MainFragment类

    public class MainFragment extends Fragment implements AsyncResponse, AdapterView.OnItemClickListener{
        public static final String PREFS = "prefFile";
        final String LOG = "MainFragment";
    
        final static String url = "http://10.0.3.2:8080/WebService/rest/get/products";
    
        private ArrayList<Products> productList;
        private ListView lv;
        FunDapter<Products> adapter;
    
        View view;
    
    
        public MainFragment() {
    
        }
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            view = inflater.inflate(R.layout.fragment_main, container, false);
    
            ImageLoader.getInstance().init(UILConfig.config(MainFragment.this.getActivity()));
    
            PostResponseAsyncTask taskRead = new PostResponseAsyncTask(MainFragment.this.getActivity(), this);
            taskRead.execute(url);
    
    
            return view;
        }
    
        @Override
        public void processFinish(String s) {
    
            productList = new JsonConverter<Products>().toArrayList(s, Products.class);
    
            BindDictionary dic = new BindDictionary();
    
            dic.addStringField(R.id.tvName, new StringExtractor<Products>() {
                @Override
                public String getStringValue(Products item, int position) {
                    return item.name;
                }
            });
    
            dic.addStringField(R.id.tvDesc, new StringExtractor<Products>() {
                @Override
                public String getStringValue(Products item, int position) {
                    return item.description;
                }
            }).visibilityIfNull(View.GONE);
    
            dic.addStringField(R.id.tvPrice, new StringExtractor<Products>() {
                @Override
                public String getStringValue(Products item, int position) {
                    return ""+item.price;
                }
            });
    
            dic.addDynamicImageField(R.id.ivImage, new StringExtractor<Products>() {
                @Override
                public String getStringValue(Products item, int position) {
                    return item.pic;
                }
            }, new DynamicImageLoader() {
                @Override
                public void loadImage(String url, ImageView img) {
                    //Set image
                    ImageLoader.getInstance().displayImage(url, img);
                }
            });
    
            dic.addBaseField(R.id.btnCart).onClick(new ItemClickListener() {
            });
    
            adapter = new FunDapter<>(MainFragment.this.getActivity(), productList, R.layout.product_row, dic);
            lv = (ListView)view.findViewById(R.id.lvProduct);
            lv.setAdapter(adapter);
    
            lv.setOnItemClickListener(this);
    
        }
    
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
        }
    }
    
    4 回复  |  直到 8 年前
        1
  •  1
  •   Tomin B Azhakathu    8 年前

    尝试使用一些库,如Reformation、Volley、Loopj等来处理异步GET或POST HTTP请求。

    要从url或文件路径实现动态图像,请使用Piccasso或Glide库。

    下面是关于这些库的一些示例和文档

    Loopj

    1. Loopj official Documentation and Example

    改装

    1. Retrofit official Documentation By SquareUp
    2. Retrofit Tutorial from JournelDev

    截击

    1. Volley official Documenation By Android Developers
    2. Volley tutorial from Journeldev

    动态图像处理

    毕加索

    Android Picasso Library

    滑行

    Glide Library for Android

    希望这些可以帮助你

    改装示例

    建筑gradle(应用程序)

            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'
    

    主要片段

    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;
            }
        }
    

    API接口

    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();
    
    }
    

    产品

    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;
        }
    }
    

    别忘了添加 <uses-permission android:name="android.permission.INTERNET" /> 在舱单中

        2
  •  0
  •   noman404    8 年前

    您正在执行POST请求 PostResponseAsyncTask 这就是为什么你 405 Method not allowed 。如果该端点接受GET,则执行GET请求。你应该使用更好的 截击 改装 网络通信图书馆。

        3
  •  0
  •   Navneet Krishna    8 年前

    尝试使用改装,首先添加以下依赖项

    compile 'com.squareup.retrofit2:retrofit:2.3.0'

    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

    首先,尝试找出您从后端得到的json响应的类型,它可以是数组响应/对象响应。

    Json数组响应的形式如下 [{"field1":"value1",..},{"field2":"value2",..}..] 鉴于对象 回复的形式如下 {"field1":"value1",..}

    您可以检查 this tutorial 了解如何解析json响应

    如果检查后端并找出响应,则可以使用相同的 http://www.jsonschema2pojo.org/

    案例1:假设您有 json object 回答 ( {“field1”:“value1”,…} )

    首先使用您的响应创建一个模型类 jsonschema2pojo 如上所述,然后像下面这样调用它(假设 YourObjectModel 是您的模型类)

    Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://10.0.3.2:8080/WebService/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    
        SampleInterface request = retrofit.create(SampleInterface.class);
        Call<YourObjectModel> call1=request.getResponse();
        call1.enqueue(new Callback<YourObjectModel>() {
            @Override
            public void onResponse(Call<YourObjectModel> call, Response<YourObjectModel> response) {
                Toast.makeText(MainActivity.this,response.body().toString(),Toast.LENGTH_SHORT).show();
            }
    
            @Override
            public void onFailure(Call<YourObjectModel> call, Throwable t) {
                Toast.makeText(MainActivity.this,t.toString(),Toast.LENGTH_SHORT).show();
            }
    
        });
    

    SampleInterface。JAVA

    public interface SampleInterface {
    @GET("rest/get/products")
    Call<YourObjectModel> getResponse();
    }
    

    案例2:假设您有 json array 回答 ( [{“field1”:“value1”,…},{“field2”:“value2”,…}….] )

    首先像上面的例子一样创建一个模型类,因为它是一个数组响应,所以您可能需要将响应作为列表来获取,所以更改所有 call 方法来自 Call<YourObjectModel> Call<List<YourArrayModel>>

    哪里 YourArrayModel 是json数组响应的模型类

        4
  •  0
  •   yathavan    8 年前

    试试这个例子,这很简单,这个例子一定对你有帮助。

    1. asynctask-callback
    2. volley-callback