2015-11-10 72 views
0

我想要做我認爲是一件簡單的事情。我需要POST數據到PHP服務器。我試過this solution,但在Apache HttpClient 4.5中,我無法在包中找到BasicNameValuePair。經過進一步的研究,我認爲我會嘗試StringEntity ... nope不在4.5中(我至少可以找到)。所以我試圖用HttpsURLConnection來做到這一點。這個問題是我無法弄清楚如何添加一個名稱到我的參數和名稱,我不知道如何使用$ _POST ['name']在PHP中訪問。Java Post數據HttpsUrlConnection或HttpClient 4.5

我當前的代碼:

String json = gson.toJson(data); 
URL url = new URL("https://www.domain.com/test.php"); 

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
conn.setDoOutput(true); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("Content-Length", String.valueOf(json.length())); 
OutputStream os = conn.getOutputStream(); 
os.write(json.getBytes()); 

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
String decodedString; 
while ((decodedString = in.readLine()) != null) { 
    System.out.println(decodedString); 
} 
in.close(); 

回答

0

嘗試使用DataOutputStream類和後沖洗掉。

DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
wr.writeChars(json); 
wr.flush(); 
wr.close();