从Android应用程序发送POST

时间:2014-04-22 09:56:50

标签: java android bufferedreader bufferedwriter

我正在向服务器发送POST请求。以下用于PC应用程序的java代码,但不适用于我的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();
}

2 个答案:

答案 0 :(得分:1)

试试这个:并考虑使用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;
}

答案 1 :(得分:1)

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