无法在android中获得okhttp3的响应

时间:2018-04-02 05:13:11

标签: android android-asynctask okhttp3

我正在使用okhttp3将图像从手机上传到服务器。我正在使用multiparty上传图片。我正在尝试使用此方法获取响应,但问题是当我尝试在"NetworkThreadException"中显示的logcat中获取响应时,我也无法从响应中获取字段。我尝试了很多东西,但都是徒劳的。我不明白该怎么做。

代码:

     private void execMultipartPost() throws Exception {


    RequestBody requestBody;

    pBar.setVisibility(View.VISIBLE);

    SessionManager session = new SessionManager(getContext().getApplicationContext());
    HashMap<String, String> user = session.getLoggedUserDetails();
    String api_token = user.get("api_token");

    if (filePath != null) {
        File file = new File(filePath);
        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        filename = "file_" + System.currentTimeMillis() / 1000L;

        Log.e("TAG", "filename: " + filename);

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", filename + ".jpg", fileBody)
                .addFormDataPart("api_token", api_token)
                .addFormDataPart("name", etName.getText().toString())
                .addFormDataPart("introduction", etGoal.getText().toString())
                .addFormDataPart("advisor_id", user.get("id"))
                .addFormDataPart("category", etCompany_name.getText().toString())
                .addFormDataPart("expertise", user.get("specialist"))
                .addFormDataPart("experience", etAge.getText().toString())
                .addFormDataPart("fb_link", et_fb_link.getText().toString())
                .addFormDataPart("feed_link", et_rss_link.getText().toString())
                .addFormDataPart("youtube_link", et_youTube_link.getText().toString())
                .addFormDataPart("linkedin_link", et_linkdenLink.getText().toString())
                .addFormDataPart("email", etMail.getText().toString())


                .build();

    } else {


        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "null")
                .addFormDataPart("api_token", api_token)
                .addFormDataPart("name", etName.getText().toString())
                .addFormDataPart("introduction", etGoal.getText().toString())
                .addFormDataPart("advisor_id", user.get("id"))
                .addFormDataPart("category", etCompany_name.getText().toString())
                .addFormDataPart("expertise", user.get("specialist"))
                .addFormDataPart("experience", etAge.getText().toString())
                .addFormDataPart("fb_link", et_fb_link.getText().toString())
                .addFormDataPart("feed_link", et_rss_link.getText().toString())
                .addFormDataPart("youtube_link", et_youTube_link.getText().toString())
                .addFormDataPart("linkedin_link", et_linkdenLink.getText().toString())
                .addFormDataPart("email", etMail.getText().toString())

                .build();


    }


    okhttp3.Request request = new okhttp3.Request.Builder()
            .url("http://url")
            .post(requestBody)
            .build();


    OkHttpClient okHttpClient = new OkHttpClient();


    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pBar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), getResources().getString(R.string.some_error_occured), Toast.LENGTH_SHORT).show();


                    e.printStackTrace();
                }
            });
        }


        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {

                        String responseStr = response.body().string();
                        Log.e("TAG", "okhttp3run: " + responseStr);

                        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.article_uploaded_successfully), Toast.LENGTH_SHORT).show();
                        //   changeFragment(new FragmentMicroLearningAdviserArticle());
                        pBar.setVisibility(View.GONE);

                    } catch (Exception e) {

                        Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.some_error_occured), Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                        pBar.setVisibility(View.GONE);
                    }
                }
            });
        }
    });
}

回应:

      {
"data": {
    "id": 14,
    "category": "ddf",
    "name": "D",
    "email": "",
    "mobile": "99",
    "introduction": "",
    "age": null,
    "gender": "F",
    "belongs_to": "A",
    "services": "12",
    "specialist": "PC",
    "fb_link": "",
    "linkedin_link": "",

   }

This is my response when I add log.e

1 个答案:

答案 0 :(得分:0)

当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask中运行代码,或创建处理程序以执行网络调用,而不是在UiThread中运行。 代码中处理程序的示例:

当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask中运行代码,或创建处理程序以执行网络调用,而不是在UiThread中运行。

代码中处理程序的示例:

private void execMultipartPost() throws Exception {

//your code till the else block here

okhttp3.Request request = new okhttp3.Request.Builder()
        .url("http://url")
        .post(requestBody)
        .build();


OkHttpClient okHttpClient = new OkHttpClient();
Handler mHandler = new Handler(Looper.getMainLooper());

okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, final IOException e) 
               mHandler.post(new Runnable() {
               @Override
                public void run() {
                    mTextView.setText(mMessage); // must be inside run()
                }
            });
        }

    @Override
    public void onResponse(Call call, final okhttp3.Response response) throws IOException {
                mHandler.post(new Runnable() {
                @Override
                public void run() {
                   try {

                    String responseStr = response.body().string();
                    Log.e("TAG", "okhttp3run: " + responseStr);

                    Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.article_uploaded_successfully), Toast.LENGTH_SHORT).show();
                    //   changeFragment(new FragmentMicroLearningAdviserArticle());
                    pBar.setVisibility(View.GONE);

                } catch (Exception e) {

                    Toast.makeText(getActivity(), 
                    getActivity().getResources().getString(R.string.some_error_occured), 
                    Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                    pBar.setVisibility(View.GONE);
                }

              }
        });
});

不要在主UI线程上运行网络调用,因为它会阻止用户执行其他任务。