android中的套接字连接

时间:2013-02-26 11:35:04

标签: android sockets

在我的应用程序中使用以下代码向服务器发送值。

public String sendHttpRequest(String params) {
    // TODO Auto-generated method stub
    URL url;
    String result = new String();
    try {
        url = new URL(AUTHENTICATION_SERVER_ADDRESS+params);
        System.out.println("url :"+url.toString());
        HttpURLConnection connection;
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
                    /*PrintWriter out = new PrintWriter(connection.getOutputStream());

        out.println(params);
        out.close();*/
        BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println("inputLine :"+inputLine);
            result = result.concat(inputLine);
        }
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (result.length() == 0) {
        result = HTTP_REQUEST_FAILED;
    }
    System.out.println("Result :"+result);
    return result;
}

params =?username = * &amp; email=a@a.com& action = signUpUser&amp; number = < / EM>的 ** * &安培;密码= &安培;端口= 21241

在此方法中,所有值都将添加到服务器。

但如果我以下面的方式做同样的事情,那么所有的vaues都没有更新。

public String sendHttpRequest(String params) {
    // TODO Auto-generated method stub
    URL url;
    String result = new String();
    try {
        url = new URL(AUTHENTICATION_SERVER_ADDRESS);
        System.out.println("url :"+url.toString());
        HttpURLConnection connection;
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);

        PrintWriter out = new PrintWriter(connection.getOutputStream());

        out.println(params);
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println("inputLine :"+inputLine);
            result = result.concat(inputLine);
        }
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (result.length() == 0) {
        result = HTTP_REQUEST_FAILED;
    }
    System.out.println("Result :"+result);
    return result;
}

为什么会这样?我做错了吗?

0 个答案:

没有答案