android - 发送POST请求时获取IOException

时间:2016-05-29 11:59:04

标签: android http android-asynctask http-post ioexception

我有以下AsyncTask:

class LoginAttempt extends AsyncTask<Pair<String, String>, Void, JSONObject> {

    private List<Pair<String, String>> params;
    private ProgressDialog loginProgress;

    @Override
    protected void onPreExecute() {
        loginProgress = new ProgressDialog(LoginActivity.this);
        loginProgress.setCancelable(false);
        loginProgress.setMessage("Се најавувам...");
        loginProgress.setIndeterminate(true);
        loginProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        loginProgress.show();
    }

    @Override
    protected JSONObject doInBackground(Pair<String, String> params[]) {
        this.params = Arrays.asList(params);
        return WebServices.makeHttpPostRequest(this.params, WebServices.LOGIN);
    }

    @Override
    protected void onPostExecute(JSONObject response) {
        loginProgress.cancel();
        try {
            if(response.getInt("status") == HttpStatuses.HTTP_OK) {
                JSONObject userCredentials = response.getJSONObject("credentials");
                login(userCredentials.getString("username"), userCredentials.getString("password"));
            } else {
                AlertDialog.Builder errConn = new AlertDialog.Builder(LoginActivity.this);
                errConn.setMessage(response.getInt("status") + ": " + response.getString("error"));
                errConn.setCancelable(true);
                errConn.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                errConn.show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            //TODO: Update error dialog when REST API is finished
            AlertDialog.Builder errConn = new AlertDialog.Builder(LoginActivity.this);
            errConn.setMessage("TEST, RABOTI BEZ KONEKCIJA");
            errConn.setCancelable(true);
            errConn.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            errConn.show();
        }
    }

}

带有makePostHttpRequest()函数的WebServices类:

public class WebServices {
public static final String CONNECTION_URL = "http://192.168.1.102/klikniobrok/";
public static final String LOGIN = "login.php";
public static final String REGISTER = "register.php";

public static JSONObject makeHttpPostRequest(List<Pair<String, String>> params, String action) {
    JSONObject requestResponse;
    try {
        StringBuilder postData = new StringBuilder();
        for(int i = 0; i < params.size(); i++) {
            if(postData.length() != 0) {
                postData.append("&");
            }
            postData.append(URLEncoder.encode(params.get(i).first, "UTF-8"));
            postData.append("=");
            postData.append(URLEncoder.encode(params.get(i).second, "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");
        URL connUrl = new URL(CONNECTION_URL + action);
        HttpURLConnection connection = (HttpURLConnection) connUrl.openConnection();
        connection.setRequestMethod(HttpMethods.POST);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.getOutputStream().write(postDataBytes);
        BufferedReader requestInputReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),
                "UTF-8"));
        StringBuilder requestInput = new StringBuilder();
        for(String line = requestInputReader.readLine(); line != null; line = requestInputReader.readLine()) {
            requestInput.append(line).append("\n");
        }
        requestInputReader.close();
        connection.disconnect();
        requestResponse = new JSONObject(requestInput.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        requestResponse = null;
    } catch (IOException e) {
        e.printStackTrace();
        requestResponse = null;
    } catch (JSONException e) {
        e.printStackTrace();
        requestResponse = null;
    }
    return requestResponse;
}

}

对AsyncTask的调用:

loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List<Pair<String, String>> loginParams = new ArrayList<>();
            loginParams.add(new Pair<>("username", username.getText().toString()));
            loginParams.add(new Pair<>("password", password.getText().toString()));
            LoginAttempt login = new LoginAttempt();
            login.execute(loginParams.toArray(new Pair[loginParams.size()]));
        }
    });

我在连接行get.utOutputStream()得到一个IOException.write(postDataBytes);

我已经在这里检查了其他问题,但是那里的答案说该异常是因为在UI线程上运行了POST请求,但是我使用AsyncTask来完成此任务。有什么问题?

我使用Postman测试了API,它按预期工作。

0 个答案:

没有答案