【问题标题】:Android JSON POST with OKHTTP带有 OKHTTP 的 Android JSON POST
【发布时间】:2016-06-10 16:08:03
【问题描述】:

我正在寻找一种使用 OKHTTP 实现 JSON-POST 请求的解决方案。我有一个 HTTP-Client.java 文件,它处理所有方法(POST、GET、PUT、DELETE),并且在 RegisterActivity 中我想将用户数据(来自输入字段)以 JSON 格式发布到服务器。

这是我的 HTTP-Client.java

    public class HttpClient{

        public static final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");

        public static OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

        public static Call post(String url, String json, Callback callback) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);

            Request request = new Request.Builder()
                    .url(url)
                    .post(body.create(JSON, json))
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callback);
            return call;
        }
}

...这是 RegisterActivity

中的 onClick-Part
btnRegRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO

                String registerData = "{\"email\":\"" + etRegisterEmail.getText().toString() + "\",\"password\":\"" + etRegisterPasswort.getText().toString() + "\"}";


                try {
                    HttpClient.post(ABSOLUTE_URL, registerData, new Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                String resp = response.body().string();
                                if (resp != null) {
                                    Log.d("Statuscode", String.valueOf(response.code()));
                                    Log.d("Body", response.body().string());
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

每次我启动应用程序时,当我单击由 FATAL EXPECTION 'android.os.NetworkOnMainThreadException' 引起的注册按钮时,它都会崩溃

我已经阅读了有关 AsyncTask 的一些内容,但我不知道具体该怎么做。

【问题讨论】:

  • 首先,看看 Retrofit with okhttp 和 GSON。对于高级版本,您可以包含 Otto 和 Dagger2 以将核心业务与前端完全分离。

标签: android json http post okhttp3


【解决方案1】:

在下面试试我的代码

  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Map<String, String> params = new HashMap<String, String>();
        params.put("msisdn", "123123");
       params.put("name", "your name");
        JSONObject parameter = new JSONObject(param);
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(JSON, parameter.toString());
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/json; charset=utf-8")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("response", call.request().body().toString());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                  Log.e("response", response.body().string());
            }


    });

【讨论】:

    【解决方案2】:

    这是因为您试图在主线程(或 UI 线程)上执行 HTTP 查询。您不应该在主线程上执行长时间的任务,因为您的应用程序会挂起,因为绘图例程是在该线程中执行的(因此他的另一个名称是“UI 线程”)。您应该使用另一个线程来提出您的请求。例如:

    new Thread(){
           //Call your post method here. 
        }.start();
    

    Android asynctask 是一个做异步工作的简单类。它首先在调用线程上执行他的“onPreExecute”方法,然后在后台线程上执行他的“doInBackground”方法,然后在调用线程中执行他的“onPostExecute”方法。

    【讨论】:

      【解决方案3】:

      尝试使用 Retrofit 库向服务器发出 Post 请求。这提供了与服务器的快速可靠的连接。
      您也可以使用 Volley 库。

      【讨论】:

        猜你喜欢
        • 2017-09-29
        • 2016-03-12
        • 2023-03-26
        • 2017-09-15
        • 2017-01-21
        • 1970-01-01
        • 2017-03-24
        • 2018-10-15
        • 2016-09-24
        相关资源
        最近更新 更多