在Android上调用POST API

tpxzln5u  于 2023-04-18  发布在  Android
关注(0)|答案(6)|浏览(126)

从Android,我尝试请求一个简单的POST-API,用一个简单的JSON对象响应。
比如说,我有一个简单的API(1.1.1.1/testApi),它用一个JSON对象进行响应,该对象包含:

  • status:状态值
  • name:名称值

Calling the API using Postman工作起来很有魅力,所以我认为我的API很好。
我已经尝试了下面的一些链接:

  1. AsyncTask:没有关于如何调用CallApi对象和解析API地址(例如URL)的示例,因此当我尝试调用该对象时总是出错。
  2. Apache HTTP Client:正如链接所说,几乎所有的答案都不支持Android 6.0
  3. Retrofit:似乎可用,但我找不到一个合适的示例来在我的案例中使用它
    我确实花了很多时间来寻找解决方案,但是显然没有“简单”的方法来调用POST-API。
    有没有一个简单的方法可以接受一个URL输入,然后返回一个JSON对象?
    让我知道这是否是一个重复的问题。
    先谢谢你了。
nc1teljy

nc1teljy1#

你好,我有工作改造的例子试试你的方式
我们开始吧
1)Gradle

compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

2)接口

public interface ServiceInterface {
@GET(HttpConstants.USERDATAJSON)
    Call<ListData>taskData(@Query("method")String method,@Query("stdID")int stdID);
}

3)服务等级

public class ServiceClass {
    static ServiceInterface serviceInterface;
//    public static final String baseUrl= HttpConstants.BASE_URL_GEONAME;
    public static final String baseUrl= HttpConstants.baseUrl;

    public static ServiceInterface connection(){
        if(serviceInterface==null){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient();
            client.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response response=chain.proceed(chain.request());
                    return response;
                }
            });
            Retrofit retrofit = new Retrofit.Builder()
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(baseUrl)
                    .build();
            serviceInterface=retrofit.create(ServiceInterface.class);
        }
        return serviceInterface;
    }
}

4)从activity调用方法

public void getTaskData(){
        ServiceInterface serviceInterface=ServiceClass.connection();
        Call<ListData> call=serviceInterface.taskData("getAllUsersSimple",0);
        call.enqueue(new Callback<ListData>() {
            @Override
            public void onResponse(Response<ListData> response, Retrofit retrofit) {
                Log.v("@@@Response",""+response.toString());
                if(response.isSuccess()){
                    listData=response.body();
                    dataList=listData.getData();
                    printStudentDetails(dataList);

                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.v("@@@Failure"," Message"+t.getMessage());
            }
        });
    }

5)波乔

public class ListData {

    @SerializedName("data")
    @Expose
    private List<DataPojo> data = null;
    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("message")
    @Expose
    private String message;

    public List<DataPojo> getData() {
        return data;
    }

    public void setData(List<DataPojo> data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}
public class DataPojo {

    @SerializedName("user_id")
    @Expose
    private String userId;
    @SerializedName("user_name")
    @Expose
    private String userName;
    @SerializedName("user_age")
    @Expose
    private String userAge;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

}

您可以使用此链接http://www.jsonschema2pojo.org/创建您的pojo
更多参考请访问链接https://github.com/pratikvyas1991/NetworkingExample/tree/master/app

brjng4g3

brjng4g32#

异步任务示例

就我个人而言,我也更喜欢根据项目的需要改造/凌空。
如果你想设置头给你(testApi)Rest API.(基本授权)

String credentials = email + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(credentials.getBytes()));
connection.setRequestProperty ("Authorization", basicAuth); 
connection..setRequestProperty("Content-Language", "en-US");

注意事项:
1.网络操作/调用不能在主线程中完成。您需要从另一个线程、异步任务或Intent服务运行它
1.所有UI操作都应在PostExecute和PreExecute上完成

任意位置调用AsyncTask

下面的代码可以帮助你。

import android.app.Activity;
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Toast;
    import org.json.JSONObject;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Map;

    public class MainActivity extends AppCompatActivity {
        String TEST_URL="http://172.16.68.4:8080/testApi";
        Activity activity;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            activity=MainActivity.this;

            new PostAsyncTask().execute();

        }

        private class PostAsyncTask extends AsyncTask<String,Void,JSONObject> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected JSONObject doInBackground(String... params) {
                String value="test";
                Map postData = new HashMap<>();
                postData.put("key",value);
                return post(TEST_URL,postData);
            }

            @Override
            protected void onPostExecute(JSONObject response) {
                super.onPostExecute(response);
                //All your UI operation can be performed here
                //Response string can be converted to JSONObject/JSONArray like
                try {
                    Toast.makeText(activity, String.format("%s : %s",response.getString("status"),response.getString("name")), Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(activity, String.format("%s","Something went wrong!!!!!!"), Toast.LENGTH_LONG).show();

                }
                System.out.println(response);
            }
        }
         /**
         * Method allows to HTTP POST request to the server to send data to a specified resource
         * @param REQUEST_URL URL of the API to be requested
         * @param params parameter that are to be send in the "body" of the request Ex: parameter=value&amp;also=another
         * returns response as a JSON object
         */
        public JSONObject post(String REQUEST_URL,Map<String, Object> params) {
            JSONObject jsonObject = null;
            BufferedReader reader = null;
            try { URL url = new URL(REQUEST_URL);
                StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setConnectTimeout(8000);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.getOutputStream().write(postDataBytes);
                connection.connect();
                StringBuilder sb;
                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    jsonObject = new JSONObject(sb.toString());
                }
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return jsonObject;
        }
    }
pcww981p

pcww981p3#

Rahmat.如果你想发送POST请求到你的Web API,你可以尝试Android Volley库.你可以参考下面的链接.
Android Volley库
Android Volley Link Here
教学
Android Hive Volley Tutorial
Dzone Volley Tutorial

v7pvogib

v7pvogib4#

就我个人而言,我更喜欢Retrofit,它真的很容易,真的很好用
http://square.github.io/retrofit/

rekjcdws

rekjcdws5#

你可以通过Restful服务使用RestTemplate,非常简单。下面是一个示例代码,我在其中发布了一个Object。

public MasterObject setMasterByBatch(MasterObject masterObject) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        masterObject = restTemplate.postForObject(yourUrl, masterObject, MasterObject.class);          

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("masterObjPost_WsCli_EX", e.toString());
    }
    return masterObject;
}

这在您的build中需要很少的依赖项。gradle(模块:app):

dependencies {
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
compile 'com.fasterxml.jackson.core:jackson-core:2.6.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.6.0'
}

如果显示关于org.springframework的任何错误,您可能需要下载并插入spring库

axkjgtzd

axkjgtzd6#

Android Manifest

<uses-permission android:name="android.permission.INTERNET" />

主要活动

API apiInterface = RestClient.getRetrofit().create(API.class);
        //JsonObject objFilterData = new JsonObject();
        //objFilterData.addProperty("params", "0");
        Call<JsonObject> call = apiInterface.apiname("0");
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                // check your full URL
                String url = response.raw().request().url().toString();

                JsonObject jsonObject = new Gson().fromJson(response.body(), JsonObject.class);
                //your response in json Object
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

RestClient

public class RestClient {

    public static String base_url = "your base url";
    public static Retrofit retrofit;

    public static Retrofit getRetrofit() {
        if (retrofit == null) {

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(100, TimeUnit.SECONDS)
                    .writeTimeout(100, TimeUnit.SECONDS)
                    .readTimeout(100, TimeUnit.SECONDS).build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(base_url)
                    .client(client)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}

接口API类

public interface API {


    @FormUrlEncoded
    @POST("apiname")
    Call<JsonObject> apiname(@Field("params") String customer_id);
    
     //@Headers("Content-Type:application/json")
     //@POST("updateselleraddress")
     //Call<JsonObject> updateselleraddress(@Body String body);

}

values/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

改装依赖项

implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.7'
 implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.7'
 implementation 'com.squareup.retrofit2:retrofit:2.9.0'
 implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'

如果需要响应类

@SerializedName("data")
    @Expose
    private ArrayList<Data> data;

    public ArrayList<Data> getData() {
        return data;
    }

    public void setData(ArrayList<Data> data) {
        this.data = data;
    }

相关问题