首页 > 解决方案 > com.androidnetworking.error.ANError: com.androidnetworking.error.ANError: PROTOCOL_ERROR

问题描述

我使用android网络连接到服务器并将图片发送到服务器,但是当我想发送时出现错误:com.androidnetworking.error.ANError:com.androidnetworking.error.ANError:我使用android网络连接到服务器并发送图片到服务器,但我想发送时出错:com.androidnetworking.error.ANError:com.androidnetworking.error.ANError:

D/خطاااااااا: com.androidnetworking.error.ANError: com.androidnetworking.error.ANError: okhttp3.internal.http2.StreamResetException: stream was reset: PROTOCOL_ERROR
D/TextView: setTypeface with style : 0
D/ViewRootImpl@c2f4955[Main]: ViewPostImeInputStage processPointer 0
D/ViewRootImpl@c2f4955[Main]: ViewPostImeInputStage processPointer 1
D/خطاااااااا: com.androidnetworking.error.ANError: com.androidnetworking.error.ANError: okhttp3.internal.http2.ConnectionShutdownException

这是程序的主体:

package com.example.myfaild;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.ParsedRequestListener;

public class LoginActivity extends AppCompatActivity {

    EditText user , pass;
    Button lgn;
    TextView viewRegister;

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

        user = this.<EditText>findViewById(R.id.editTextUsername);
        pass = this.<EditText>findViewById(R.id.editTextPassword);
        lgn = this.<Button>findViewById(R.id.buttonLogin);
        viewRegister = this.<TextView>findViewById(R.id.textViewRegister);


        final SessionManager manager = new SessionManager(this);
        if (manager.isLoggedIn()){
            startActivity(new Intent(LoginActivity.this, Main.class));
            finish();
        }



        AndroidNetworking.initialize(this);


        viewRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, SignUp.class));
                finish();

            }
        });

        lgn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user.length()==0 || pass.length()==0){
                    Snackbar.make(v,  "فیلد ها باید پرشود ! ", Snackbar.LENGTH_LONG).show();
                    return;

                }
               login(user.getText().toString(),pass.getText().toString(),manager, v);
            }
        });


    }


    private void login (final String username, String password, final  SessionManager manager , final View v){
        AndroidNetworking.post(URLS.host+URLS.login)
                .addBodyParameter("username",username)
                .addBodyParameter("password",password)
                .setTag("LOGIN")
                .build()
                .getAsObject(User.class, new ParsedRequestListener<User>() {
                    @Override
                    public void onResponse(User response) {
                        if (response.getUsername().toLowerCase().equals(username.toLowerCase())){
                         manager.setLoggedIn(true);
                            SharedPreferences preferences = getSharedPreferences("pref", MODE_PRIVATE);
                            preferences.edit().putString("username",response.getUsername()).apply();
                            preferences.edit().putString("email", response.getUsername()).apply();
                            preferences.edit().putString("image", response.getImageUrl()).apply();
                            startActivity(new Intent(LoginActivity.this, Main.class));
                            finish();
                        }else{
                            Snackbar.make(v,  "نام کاربری و رمز عبور مطابقت ندارد ! ", Snackbar.LENGTH_LONG).show();
                        }

                    }

                    @Override
                    public void onError(ANError anError) {
                        Log.d("خطاااااااا" ,String.valueOf(anError));
                        Snackbar.make(v,  "خطا در ارتباط ! ", Snackbar.LENGTH_LONG).show();

                    }
                });

    }
}

标签: javaandroidandroid-studio

解决方案


您提供的error-log内容不足以解决问题。使用下面的代码进行测试,可能会看到更好的error-log.

//Somewhere in your code, call the `testApi` method:
HashMap<String,String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
testApi(params);

将以下方法添加到您的类中:

 public static void testApi (final HashMap<String,String> params) {
    getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            try {
                String url = "your-url";
                JSONParser jsonParser = new JSONParser();
                JSONObject jsonObject = jsonParser.getJSONFromUrlByPost(url, params, null);
                //check and see if the result is ok
                Log.i("test_api", "success");
            } catch (Exception e) {
                //check the exception here
                Log.i("test_api", "error:");
                e.printStackTrace();
            }

        }
    });

}


public static ExecutorService getExecutor() {
    ExecutorService exService = Executors.newFixedThreadPool(1);
    return exService;
}


//posts some parameters, gets input stream, turns it to jason object and return the jason object
public JSONObject getJSONFromUrlByPost(String url,
                                       HashMap<String, String> params, HashMap<String, String> header) {
    URL myUrl;
    String response = "";
    try {
        myUrl = new URL(url);

        HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
        conn.setRequestMethod("POST");

        if (header != null)
            for (Map.Entry<String, String> entry : header.entrySet())
                conn.setRequestProperty(entry.getKey(), entry.getValue());

        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(params));
        writer.flush();
        writer.close();
        os.close();
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "" + responseCode;
        }
    } catch (Exception e) {
         e.printStackTrace();
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(response);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // return JSON String
    return jObj;

}


public String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}

推荐阅读