使用OkHttp时我的应用程序崩溃了

时间:2017-10-22 17:47:03

标签: java android post okhttp

当我尝试使用OkHttp发送帖子请求时,手机上的应用程序(LG g3)崩溃没有错误。

btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "login=test&pasword=test");
            Request request = new Request.Builder()
                    .url("http://myUrl")
                    .post(body)
                    .build();
            try {
                Response response = client.newCall(request).execute();

                txtRequest.setText(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你正在主线程上执行网络调用,这是我猜你得到的异常。使用AsyncTask,您的问题就解决了。这是您的代码的更正版本。 的被修改

    package com.example.nisu.postrequest;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SendPost extends AppCompatActivity {

    Button btnSend;
    TextView txtRequest;
    OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_post);

        btnSend = (Button) findViewById(R.id.btnSend);
        txtRequest = (TextView) findViewById(R.id.txtRequest);

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Request request = new Request.Builder()
                        .url("http://httpbin.org/ip").get()
                        .build();
                new MyAsyncTask().execute(request);
            }
        });
    }

    class MyAsyncTask extends AsyncTask<Request, Void, Response> {

        @Override
        protected Response doInBackground(Request... requests) {
            Response response = null;
            try {
                response = client.newCall(requests[0]).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(Response response) {
            super.onPostExecute(response);
            try {
                txtRequest.setText(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}