无法通过Https

时间:2015-11-23 07:12:29

标签: java php android post https

我有一个简单的Android应用程序需要向我的PHP服务器发送消息,该服务器将返回一些数据。我能够从服务器返回数据,但我无法发送任何数据。它可能是愚蠢的东西,但我无法弄明白。请注意,此处的网址不是真正的网址。

public void addUser(User user, String password) throws Exception {

    URL url = new URL("https://someuser.c9users.io/service.php");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    // set Timeout and method
    conn.setRequestMethod("POST");
    conn.setReadTimeout(7000);
    conn.setConnectTimeout(7000);
    conn.setRequestProperty("op", "adduser");
    conn.setDoOutput(true);
    conn.setRequestProperty("username",user.getUserName());
    conn.setRequestProperty("email",user.getEmail());
    conn.setRequestProperty("password", password);
    if(user.getBirthDate() != null)
        conn.setRequestProperty("birthdate", user.getBirthDate().toString());
    if(user.getProfImage() != null)
        conn.setRequestProperty("profile_image", "some path to img");

    //conn.connect(); if I leave the code it does NoFileFoundException. why?
    InputStream is = conn.getInputStream();
    String result="";
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        result += inputLine;
    }

}    

我的PHP代码:

function print_post_get() {
    echo "post&get vals: ";
    foreach($_POST as $key => $value) {
        echo $key.":".$value." \n";
    }
    foreach($_GET as $key => $value) {
        echo $key.":".$value." \n";
    }
}

//print all post and get
print_post_get();
//get method form post
if(empty($_POST['op']))
die('no operation?');

switch($_POST['op']) {

    case 'adduser':
        $retval = adduser();
        if($retval) //couldn't add user
            echo $retval;
        break;

    case 'removeuser': 
        $retval = removeuser();
        if($retval)
            echo $retval;
        break;
    case 'getuser':
        $retval = getuser();
        echo $retval;
        break;
    default:
        echo "unknow op.";
        break;
}

1 个答案:

答案 0 :(得分:3)

我最近遇到了类似的问题。我发现setRequestProperty添加到标题中,而不是POST正文。但是

conn.setDoOutput(true)

允许您连接到

outStream = conn.getOutputStream()

现在,您可以使用android.net.Uri.Builder创建POST数据。

Uri.Builder builder = new Uri.Builder()
    .appendQueryParameter("username",user.getUserName())
    .appendQueryParameter("email",user.getEmail());

写入流getEncodedQuery()

try (OutputStream outStream = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(outStream, "UTF-8"))) {
    String query = builder.build().getEncodedQuery();
    writer.write(query);
 }

现在,您可以使用conn发布请求。