I am a newbie to Android Java
and I would like to convert my web project and react native project to Android Java Apps.
for Website, I using Jquery and ajax
$.ajax({
url: "https://site/data.json",
data: JSON.stringify({
Name: "Peter",
Gender: "M"
}),
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(returnData){
},
error: function(xhr, ajaxOptions, thrownError){
}
})
For React Native ,I using fetch
//Work with React Native
fetch('https://site/data.json',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Name: "Peter",
Gender: "M"
})
}
But I have not idea convert it to Android Java. any idea??
Thank you very much
I tried the following code, but not work for me.
public void sendPost() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("https://site/data.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("Name:", "Peter");
jsonParam.put("Gender:", "M");
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});