java - HttpURLConnection 发布 Android

标签 java android http http-post httpurlconnection

我正在尝试使用教程 here用我学到的数据here执行 HTTPUrlConnection POST 请求。每次我运行它时,响应都会给出错误消息:“您必须输入用户名!”和“您必须输入密码”。谁能解释为什么服务器无法识别甚至无法获取发布的数据?这是我的代码:

class urlRequest extends AsyncTask<String, String, String> {

protected String doInBackground(String... all) {
            URL url;
            String response = "";
            try {
                String requestURL = "https://hac.chicousd.org/LoginParent.aspx?page=GradebookSummary.aspx";
                url = new URL(requestURL);

                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty( "charset", "utf-8");
                conn.setRequestProperty( "Content-Length", Integer.toString(getPostDataString(postDataParams).length()));
                conn.setFixedLengthStreamingMode(getPostDataString(postDataParams).length());


                JSONObject postDataParams = new JSONObject();
                postDataParams.put("checkCookiesEnabled", "true");
                postDataParams.put("checkMobileDevice", "false");
                postDataParams.put("checkStandaloneMode", "false");
                postDataParams.put("checkTabletDevice", "false");
                postDataParams.put("portalAccountUsername", "username");
                postDataParams.put("portalAccountPassword", "password");

                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                writer.write(getPostDataString(postDataParams)); // returns: checkCookiesEnabled=true&checkMobileDevice=false&checkStandaloneMode=false&checkTabletDevice=false&portalAccountUsername=username&portalAccountPassword=password

                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line=br.readLine()) != null) {
                        response+=line;
                        Log.i("tag", line);
                    }
                }
                else {
                    response="";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    return response;
           }

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}

最佳答案

使用 POST 发送参数:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("portalAccountUsername", "username");
jsonParam.put("portalAccountPassword", "password");

你错过的部分在下面......即,如下......

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

关于java - HttpURLConnection 发布 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421519/

相关文章:

c# - Facebook SDK - 处理应用程序邀请?

python - web.py:如何为任何 HTTP 方法选择性地隐藏带有 404 的资源?

http - 通过powershell在IIS上设置文件html响应头缓存控制

java - 类型中的方法不适用于参数(即使它们适用?!)

java - 在没有所有必要数据的情况下修补 Google 事件开始日期和结束日期

java - 在较大的文件上出现 java.lang.OutOfMemoryError

Android - Viewpager 和 fragment ,方法不起作用

http - 无法访问我的网站 ERR_TOO_MANY_REDIRECTS

具有http多部分formdata POST方法的Java套接字

java - 如果在 Websphere 8.5 中启用了 SSL,则无法查找