使用HttpURLConnetion发出POST请求并从服务器读取响应 - Android

时间:2015-10-05 21:25:23

标签: java android http-post

我是Android的新手。我在StackOverflow中也经历过许多类似的问题,但无法得到一个要点。

我正在使用用户名和密码向服务器发送帖子请求。我的服务器只检查凭据是否为真,并发送“成功”或“失败”响应。我只需要抓住服务器的响应 - 这就是全部。以下是我到目前为止所遇到的情况。

public String CheckUserAuthentication(String name, String pass) {
    try {
        URL url = new URL("http://sample.com?username=" + name + "&password=" + pass);
        try {

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);

        } catch (IOException e) {
        }

    } catch (MalformedURLException e) {

    }
    return Response;
}

如果有人建议我下一步转发请求并从服务器接收回复,我会很高兴。

3 个答案:

答案 0 :(得分:0)

我附上了一个你需要的例子的链接。对于android来说它不是100%,但代码应该在android平台上工作(是Java,duh)。

只需复制,粘贴并进行必要的修改。

干杯, 鲍勃

http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

答案 1 :(得分:0)

试试这个

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);

    DataOutputStream outputStream = new DataOutputStream(con.getOutputStream());

    String jsonParamsString = "{\"key\":\"value\"}";
    outputStream.writeBytes("request=" + jsonParamsString);
    outputStream.flush();
    outputStream.close();

    // get response
    InputStream responseStream = new BufferedInputStream(con.getInputStream());
    BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
    String line = "";
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = responseStreamReader.readLine()) != null) {
        stringBuilder.append(line);
    }
    responseStreamReader.close();

    String response = stringBuilder.toString();
    JSONObject jsonResponse = new JSONObject(response);

结果是响应然后转换为json对象,然后你可以解析它。

答案 2 :(得分:0)

使用 AsyncTask 赞这个

new MyTaskLogin().execute(Constant.LOGIN_URL + "&email=" + strUserEmail
                    + "&password=" + strUserPassword );

AsynchTask代码: -

private class MyTaskLogin extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        bar.setVisibility(View.VISIBLE);
        layout.setVisibility(View.INVISIBLE);
    }

    @Override
    protected String doInBackground(String... params) {
        return JsonUtils.getJSONString(params[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        bar.setVisibility(View.GONE);

        if (null == result || result.length() == 0) {
            setSweetDialog(SweetAlertDialog.ERROR_TYPE,
                    getString(R.string.conn_msg1),
                    getString(R.string.nodata));

        } else {

            try {
                JSONObject mainJson = new JSONObject(result);
                JSONArray jsonArray = mainJson
                        .getJSONArray(Constant.USER_LOGIN_ARRAY);
                JSONObject objJson = null;
                for (int i = 0; i < jsonArray.length(); i++) {
                    objJson = jsonArray.getJSONObject(i);
                    if (objJson.has(Constant.USER_LOGIN_MSG)) {
                        strMessage = objJson
                                .getString(Constant.USER_LOGIN_MSG);
                        Constant.GET_SUCCESS_MSG = objJson
                                .getInt(Constant.USER_LOGIN_SUCESS);
                    } else {
                        Constant.GET_SUCCESS_MSG = objJson
                                .getInt(Constant.USER_LOGIN_SUCESS);
                        strUserEmail = objJson
                                .getString("string_name1");
                        strUserName = objJson
                                .getString("string_name2");

                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            setResult();
        }

    }
}