我需要使用POST
將JSON
字符串發送到url
。 該字符串應該是:使用POST使用HttpURLConnection發送json數據
data={"cmd":"sign_in",....}
所以在doInBackground
,我用這個代碼:
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String json = "{\"cmd\": \"sign_in\",...";
try{
URL url = new URL("https://...?data=");
connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(json);
osw.flush();
osw.close();
}
我檢查使用
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseMessage.length()>0)
return true;
我的反應,但我沒有收到任何迴應。響應字符串應該是JSON
字符串。但我使用length()
來查看是否有任何字符串正在返回。 這段代碼應該工作嗎?任何幫助?
所以,你在哪裏發佈的數據作爲_Json_? – Piyush
當你在android之外嘗試它時API是否工作? –
Neeraj,API正在工作。 – Amit