通过httpurlconnection更改HttpPost

时间:2017-07-31 12:01:14

标签: android httpclient httpurlconnection

我有一种方法可以将一些数据发送到服务器并得到一个cookie响应。这是我的方法:

 public Cookie getCookie(String username, String password) {

    try {
        JSONObject obj = new JSONObject();
        key = UUID.randomUUID().toString();
        userEncrypt = .....
        passwordEncrypt = ......
        obj.put("username", userEncrypt);
        obj.put("password", passwordEncrypt);
        obj.put("customCredential", key + ",Mobile" + deviceId);
        obj.put("isPersistent", false);

        HttpPost request = new HttpPost(AppUtil.getConfig(baseActivity, App.SERVICE_AUTH) + "Login");
        request.setHeader("Content-Type", "application/json; charset=utf-8");
        request.setEntity(new StringEntity(obj.toString(), "utf-8"));
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);

            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (result.toLowerCase(Locale.US).equals("true")) {

            for (Cookie cookie : client.getCookieStore().getCookies()) {
                if (cookie.getName().contains(".ASPXAUTH"))
                    return cookie;
            }
        }

我想使用httpurlconnection,但我不知道如何更改它?我如何通过httpurlconnection返回cookie?

这是我写的新方法:

           String result = "";
        HttpURLConnection connection = null;
        connection = (HttpURLConnection) new URL(AppUtil.getConfig(this, App.SERVICE_AUTH) + "Login").openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        OutputStream os = connection.getOutputStream();
        os.write((obj.toString()).getBytes("UTF-8"));
        os.flush();

        int responseCode = connection.getResponseCode();

我在responseCode上获得了400分。有人可以帮忙吗?thnx

2 个答案:

答案 0 :(得分:1)

使用它,希望它有效。

 BufferedWriter  writer = new BufferedWriter(
                new OutputStreamWriter(outputStream, "UTF-8"));

 String s = "yourJsonName =" json.toString();
 writer.write(s);
 writer.flush();
 writer.close();

并且为了获取cookie并使用下一个请求再次发送它,您可以执行此操作:

SharedPreferences preferences = this.getSharedPreferences("CommonPrefs",
                        Activity.MODE_PRIVATE);
                if (!preferences.getString("cookieName", "no_cookie").equals("no_cookie")) {
                    connection.setRequestProperty("Cookie", preferences.getString("cookieName", "no_cookie"));
                }

                for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
                    SharedPreferences.Editor editor = preferences.edit();
                    if (headerName.equals("Set-Cookie")) {
                        String cookie = connection.getHeaderField(i);
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                        editor.putString("cookieName", cookie);
                        editor.apply();
                        break;
                    }
                    editor.putString("cookieName", "no_cookie");
                }

                connection.connect();

为了让json退出inputStream,我强烈建议你像下面一样使用Gson:

private ArrayList<YourClassOfObject> readJson(InputStream is) throws IOException {

    ArrayList<YourClassOfObject> c = new ArrayList<>();
    try{

        Reader reader = new InputStreamReader(is , "UTF-8");
        Gson gson = new Gson();
        YourClassOfObject[] p;
        p = gson.fromJson(reader, YourClassOfObject[].class);
        c.addAll(Arrays.asList(p));

    }catch (IOException e) {
        e.printStackTrace();
    }catch (Exception e){
        e.printStackTrace();
    }catch (ExceptionInInitializerError e){
        e.printStackTrace();
    }
    return c;
}

答案 1 :(得分:0)

使用Retrofit。

您将使用注释来描述HTTP请求,默认情况下会集成URL参数替换和查询参数支持。此外,它还提供自定义标头,多部分请求正文,文件上载和下载,模拟响应等功能。在后面的教程中,我们将更详细地介绍所有这些内容。

https://futurestud.io/tutorials/retrofit-getting-started-and-android-client