如果你想編寫自己的方法: 這是一個。
private JsonObject postJsonObject(JsonObject jsonObject) {
JsonObject nullresult = new JsonObject();
nullresult.addProperty("success",-1);
try {
String data = jsonObject.toString();
URL object = new URL(url); \\MENTION YOUR URL HERE
HttpURLConnection httpURLConnection = (HttpURLConnection) object.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
OutputStreamWriter wr = new OutputStreamWriter(httpURLConnection.getOutputStream());
wr.write(data);
wr.flush();
StringBuilder sb = new StringBuilder();
int HttpResult = httpURLConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
}
JsonObject result = new JsonParser().parse(sb.toString()).getAsJsonObject();
if(result !=null)
return result;
else
return nullresult;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedJsonException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return nullresult;
}
您還可以使用庫如Ion
。 鏈接:https://github.com/koush/ion
這是很容易理解android的網絡庫。他們有可以幫助你的例子。