【问题标题】:change HttpPost by httpurlconnection通过 httpurlconnection 更改 HttpPost
【发布时间】:2018-01-06 23:55:43
【问题描述】:

我有一个方法可以向服务器发送一些数据并得到一个 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

【问题讨论】:

    标签: android httpclient httpurlconnection


    【解决方案1】:

    使用改造。

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

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

    【讨论】:

      【解决方案2】:

      使用这个,希望它有效。

       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();
      

      为了从 inputStream 中获取 json,我强烈建议您使用 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;
      }
      

      【讨论】:

      • 亲爱的 milad 这是什么:yourJsonName ?my json 没有命名!!
      • 选择一个随机名称,以便在服务器端您可以使用密钥获取它,就像键和值一样。
      • 我无权访问服务器。此服务器使用上述代码,我想更改客户端代码,因为此代码已弃用。
      • 我在步骤中去世了,但是当我得到服务器的响应时,我收到了 True :-(。我必须从服务器接收 json。这是我的 inputStream :codepad.org/0Aqr0cqJ
      • 而不是 client.getCookieStore().getCookies() 我必须在 HttpURLConnection 上使用什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 2018-11-03
      • 2012-07-17
      • 1970-01-01
      相关资源
      最近更新 更多