在android上调用POST API

时间:2017-06-01 07:50:02

标签: android api android-studio

在Android上,我正在尝试使用简单的JSON对象请求一个简单的POST-API。

说,我有一个简单的API(1.1.1.1/testApi),它响应了一个包含以下内容的JSON对象:

  • 状态:状态值
  • 名称:名称值

Calling the API using Postman就像一个魅力,所以我认为我的API很好。

我已经尝试了下面的一些链接:

  1. AsyncTask:没有关于如何调用CallApi对象并解析API地址(例如URL)的示例,因此当我尝试调用对象时总会出错。
  2. Apache HTTP Client:正如链接所说,几乎所有答案都已弃用Android 6.0
  3. Retrofit:似乎可以使用,但在我的案例中找不到合适的例子
  4. 我确实花时间搜索有关此问题的解决方案,但是没有“简单”方法来调用POST-API。

    是否有任何简单的方法接受URL输入,然后返回JSON对象?

    如果这是一个重复的问题,请告诉我。

    提前致谢。

5 个答案:

答案 0 :(得分:2)

您好我有工作改造示例以您的方式尝试

让我们开始

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)从活动中调用方法

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) Pojo

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

}

您可以使用此链接创建您的pojo http://www.jsonschema2pojo.org/

有关更多参考,请访问该链接 https://github.com/pratikvyas1991/NetworkingExample/tree/master/app

答案 1 :(得分:1)

拉​​玛特。如果您希望向Web API发送POST请求,可以尝试使用Android Volley Library。您可以参考以下链接。

Android排球图书馆

Android Volley Link Here

教程

Android Hive Volley Tutorial

Dzone Volley Tutorial

答案 2 :(得分:1)

您可以使用 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(Module: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 的任何错误,您可能需要下载并插入弹簧库

答案 3 :(得分:1)

AsyncTask示例

我个人也更喜欢Retrofit / Volley,具体取决于项目需求。

如果要为您设置标题(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. 无法在主线程中进行网络操作/调用。您需要从另一个线程,异步任务或意向服务

  2. 运行它
  3. 所有UI操作都应该在onPostExecute,onPreExecute

  4. 上完成

    在您想要的地方调用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;
            }
        }
    

答案 4 :(得分:0)

就个人而言,我更喜欢Retrofit,使用

非常简单,非常好用

http://square.github.io/retrofit/