【问题标题】:Sending POST from Android Application从 Android 应用程序发送 POST
【发布时间】:2014-04-22 09:56:50
【问题描述】:

我正在尝试向服务器发送 POST 请求。以下 java 代码适用于 PC 应用程序,但不适用于我的 Android 应用程序。添加了 Iternet 权限,那么,我必须做什么才能发送这篇文章,以及我必须使用哪些其他方法和库来替换 Android 的这段代码?

      String hostname = "xxxxxxx.box"; 
      int port = 80;
      InetAddress  addr = InetAddress.getByName(hostname);
      Socket sock = new Socket(addr, port); 
      String SID = new classSID("xxxxxx").obtainSID();
      BufferedWriter  wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
      String str = "enabled=on&username="+givenName+"&email="+givenEmail+"&password="+givenPassword+"&frominternet=on&box_admin_rights=on&phone_rights=on&homeauto_rights=on&uid=&sid="+SID+"&apply=";

       ////////////////////////////////////////////////////////////////////////////////////////////
       wr.write("POST /system/boxuser_edit.lua HTTP/1.1");
       wr.write("Host: xxxxxx:80" + "\r\n");
       wr.write("Accept: text/html"  + "\r\n");
       wr.write("Keep-Alive: 300" + "\r\n"); 
       wr.write("Connection: Keep-Alive"  + "\r\n");
       wr.write("Content-Type: application/x-www-form-urlencoded"+"\r\n");
       wr.write("Content-Length: "+str.length()+"\r\n");
       wr.write("\r\n");
       wr.write(str+"\r\n");
       wr.flush();
     ////////////////////////////////////////////////////////////////////////////////////////////           
       BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream(),"UTF-8"));  
       String line;  
       while((line = rd.readLine()) != null)  
           Log.v("Response", line);     

       wr.close();
       rd.close();
       sock.close();
}

【问题讨论】:

  • 您好,我试图捕捉错误,但错误不存在。就是不行。
  • 考虑使用 ip 而不是主机名,并使用我在下面提供的代码进行测试

标签: java android bufferedreader bufferedwriter


【解决方案1】:

问题在于在端口 80 上创建套接字。您需要 root 权限才能访问 android 中的端口 issue

【讨论】:

    【解决方案2】:

    试试这个:并考虑使用 IP 而不是主机名,因为您的 android 设备可能无法解析本地主机名

    private static final String     UTF_8       = "UTF-8";
    /**
     * @param hostNameOrIP
     *            : the host name or IP<br/>
     * @param webService
     *            : the web service name<br/>
     * @param classOrEndPoint
     *            : the file or end point<br/>
     * @param method
     *            : the method being called<br/>
     * @param parameters
     *            : the parameters to be sent in the message body
     * @return
     */
    public static String connectPOST(final String url, final HashMap<String, String> parameters) {
        final StringBuilder postDataBuilder = new StringBuilder();
        if (null != parameters) {
            for (final HashMap.Entry<String, String> entry : parameters.entrySet()) {
                if (postDataBuilder.length() != 0) {
                    postDataBuilder.append("&");
                }
                postDataBuilder.append(entry.getKey()).append("=").append(entry.getValue());
            }
        }
    
        final StringBuffer text = new StringBuffer();
        HttpURLConnection conn = null;
        OutputStream out = null;
        InputStreamReader in = null;
        BufferedReader buff = null;
        try {
            final URL page = new URL(url);
            conn = (HttpURLConnection) page.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            out = conn.getOutputStream();
            final byte[] postData = postDataBuilder.toString().getBytes(UTF_8);
            out.write(postData);
            out.flush();
            out.close();
            final int responseCode = conn.getResponseCode();
            if ((responseCode == 401) || (responseCode == 403)) {
                // Authorization Error
                Log.e(TAG, "Authorization error in " + url + "(" + postDataBuilder.toString() + ")");
                // throw new Exception("Authorization Error in " + method + "("
                // + postDataBuilder.toString() + ")");
                return null;
            }
            if (responseCode == 404) {
                // Authorization Error
                Log.e(TAG, "Not found error in " + url + "(" + postDataBuilder.toString() + ")");
                // throw new Exception("Authorization Error in " + method + "("
                // + postDataBuilder.toString() + ")");
                return null;
            }
    
            if ((responseCode >= 500) && (responseCode <= 504)) {
                // Server Error
                Log.e(TAG, "Internal server error in " + url + "(" + postDataBuilder.toString() + ")");
                // throw new Exception("Internal Server Error in " + method +
                // "("
                // + postDataBuilder.toString() + ")");
                return null;
            }
            in = new InputStreamReader((InputStream) conn.getContent());
            buff = new BufferedReader(in);
            String line;
            while ((null != (line = buff.readLine())) && !"null".equals(line)) {
                text.append(line + "\n");
            }
            buff.close();
            buff = null;
            in.close();
            in = null;
            conn.disconnect();
            conn = null;
        } catch (final Exception e) {
            Log.e(TAG, "Exception while connecting to " + url + " with parameters: " + postDataBuilder + ", exception: " + e.toString() + ", cause: "
                    + e.getCause() + ", message: " + e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (final IOException e1) {
                }
                out = null;
            }
            if (null != buff) {
                try {
                    buff.close();
                } catch (final IOException e1) {
                }
                buff = null;
            }
            if (null != in) {
                try {
                    in.close();
                } catch (final IOException e1) {
                }
                in = null;
            }
            if (null != conn) {
                conn.disconnect();
                conn = null;
            }
        }
        final String temp = text.toString();
        if (text.length() > 0) {
            Log.i(TAG, "Success in " + url + "(" + postDataBuilder.toString() + ") = " + temp);
            return temp;
        }
        Log.w(TAG, "Warning: " + url + "(" + postDataBuilder.toString() + "), text = " + temp);
        return null;
    }
    

    【讨论】:

    • 附注您不需要为端口 80 指定端口
    • 你好Shereef,你能告诉我Communication类来自哪里,为什么(InputStream)会抛出错误?非常感谢!
    • 抱歉修复了,通信类是我的类我删除了所有对它的引用
    猜你喜欢
    • 2014-02-19
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多