使用okhttp发送数据而不使用异步任务

时间:2015-11-02 20:42:25

标签: android okhttp

我可以使用这种方式使用Okhttp将字符串上传到服务器吗?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

     usernam = (EditText) findViewById(R.id.username);
     passw = (EditText) findViewById(R.id.password);
     email = (EditText) findViewById(R.id.email);

     name = usernam.getText().toString();
     pass = passw.getText().toString();
     emails = email.getText().toString();

}


private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    String json = "";

    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("name",name );
    jsonObject.accumulate("password",pass );
    jsonObject.accumulate("email",emails );

    json = jsonObject.toString();

    RequestBody formBody = new FormEncodingBuilder()
            .add("result", json)
            .build();
    Request request = new Request.Builder()
            .url("https://justedhak.comlu.com/receiver.php")
            .post(formBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

2 个答案:

答案 0 :(得分:2)

如果你想在没有AsyncTask的情况下使用OkHttp,你可以参考下面的示例代码,希望这有帮助!

public class MainActivity extends AppCompatActivity {
    private static final String LOG_TAG = "OkHttp";
    private TextView mTextView;
    private Handler mHandler;
    private String mMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.textView);
        mHandler = new Handler(Looper.getMainLooper());
        OkHttpClient client = new OkHttpClient();
        // GET request
        Request request = new Request.Builder()
                .url("http://...")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                mMessage = e.toString();
                Log.e(LOG_TAG, mMessage); // no need inside run()
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(mMessage); // must be inside run()
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                mMessage = response.toString();
                Log.i(LOG_TAG, mMessage); // no need inside run()
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(mMessage); // must be inside run()
                    }
                });
            }
        });
    }
}

答案 1 :(得分:1)

网络调用必须在UI线程之外完成,所以没有。

此外,您永远不会在您的活动中调用您的Run()方法,因此不会执行

编辑:Max Pino是正确的,因为RXJava可以用来轻松地进行这种调用,但仍然会在不同的线程上执行调用