我有复杂的JSON对象,我想通过HTTP POST请求发布到服务器。 我见过很多关于Volley库的例子,但它们都只能用简单的键值对(HashMap)。 任何人都可以建议一个处理复杂JSON对象发布的库吗?
答案 0 :(得分:0)
我不知道任何与JSONObjcet一起使用的库的引用,但我在这里有一个使用AsyncTask的工作代码,它将JSONObjects发送到服务器:
private class BackgroundOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params)
//Your network connection code should be here .
String response = postCall("Put your WebService url here");
return response ;
}
@Override
protected void onPostExecute(String result) {
//Print your response here .
Log.d("Post Response",result);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
public static String postCall(JSONObject josnobj) {
String result ="";
try {
//Connect
HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//Call parserUsuarioJson() inside write(),Make sure it is returning proper json string .
writer.write(josnobj.toString());
writer.close();
outputStream.close();
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
现在,您可以使用以下代码从您的活动的onCreate()函数中调用以上内容。
JSONObject jobj = new JSONObject();
jobj.put("name","yourname");
jobj.put("email","mail");
jobj.put("pass","pass");
new BackgroundOperation().execute(jobj.toString());
注意:不要忘记在manifest.xml中提及以下权限
<uses-permission android:name="android.permission.INTERNET" />