android将值传递给post方法

时间:2015-10-06 14:20:47

标签: android post parameters

以下是使用post方法命中登录服务器的代码。

这里我需要传递4个以json格式发送的值

  public static LoginPageResponse checkLogin(Context context, String username, String password) throws Exception {

        String ID = "xxxxxxxxxxxxxxxxxxxxx";
        String roleID = "1";
        String configParams = Utils.configWithNeededParams(new LoginPost(username, password, ID, roleID));

        Map<String,String> nameValuePairs = new HashMap<String, String>();
        nameValuePairs.put("",configParams);


        InputStream inputStream = HTTPHelper.executePostAsInputStream(context, getUrl(Constant.LOGIN_JSON), nameValuePairs);
        if (inputStream == null) {
            return null;
        }
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

        GsonBuilder gson = new GsonBuilder();
        try {
            LoginPageResponse loginResponse = gson.create().fromJson(inputStreamReader, LoginPageResponse.class);
            return loginResponse;
        } catch (JsonSyntaxException e) {
            throw new JsonSyntaxException("Issue parsing server Login data. Please try again later.", e);
        }
    }

    public static InputStream executePostAsInputStream(Context context, String pageUrl,  Map<String,String> nameValuePairs) throws IOException, IllegalAccessException {
        URL url = new URL(pageUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(20000);
        conn.setConnectTimeout(20000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        os.close();

        conn.connect();

        // read the response
        System.out.println("Response Code: " + conn.getResponseCode());
        //InputStream in = new BufferedInputStream(conn.getInputStream());
        InputStream in = conn.getInputStream();
        String response = in.toString();
        System.out.println(response);
        return in;
    }

json格式添加在Map nameValuePairs中,我不知道如何添加参数和我的网址

1 个答案:

答案 0 :(得分:0)

您可以通过将请求的标头参数设置为接受JSON,将JSONObject直接发布到服务器。你这样做:

首先设置请求的标头参数......

httpsURLConnection.setRequestProperty("Content-Type", "application/json"); //header params
httpsURLConnection.setRequestProperty("Accept", "application/json"); //header params 

然后直接将JSONObject直接发送到服务器......

outputStreamWriter = new OutputStreamWriter(httpsURLConnection.getOutputStream());
outputStreamWriter.write(someJsonObject.toString());