java - 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();
}
});
}
}
解决方案
您提供的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();
}
推荐阅读
- python - 从 2D Numpy 数组中获取前 N 个值及其坐标
- git - 如何配置 Git 或 Gitlab,以便只允许分支的所有者推入它?
- splunk - 需要在 Splunk 中创建一个嵌套表或多列的表
- r - 在 R 的子函数中使用两列
- vb6 - 没有特定 DLL 引用的 VB6 项目编译
- twitter-bootstrap - 如何使我的 Bootstrap 日期选择器工作,是否有“官方”Bootstrap 3 日期选择器?
- spring - Spring Security:反向代理后面的 X509(预)身份验证
- python - 如何在不调用 Python 中的方法的情况下更改类中的属性值?
- hibernate - Hibernate Unknown 列字段列表“clazz_”
- javascript - Access-Control-Allow-Headers 它究竟做了什么以及为什么将它包含在响应中?