【发布时间】:2016-12-12 10:24:26
【问题描述】:
我想使用 HttpURLConnection 将嵌套的 JSON 发布到服务器。我得到的响应状态为 200。但值没有输入到数据库中。我的JSON如下
{
"id": "C2015300_1481039931",
"data":
{
"customerId": "C2015300",
"arrivedTime": "1481039931",
"storeCode": "100"
}
}
我在另一个异步任务的 onPostExecute() 中调用我的异步任务进行 POST,例如:-
jsonObject = new JSONObject();
finalJson = new JSONObject();
jsonObject.put("customerId", "C2015300");
Long tsLong = System.currentTimeMillis() / 1000;
ts = tsLong.toString();
jsonObject.put("arrivedTime", ts);
Log.d("time", ts);
jsonObject.put("storeCode", storecode);
finalJson.put("id", "C2015300_1481039931");
finalJson.put("data", jsonObject);
UploadTask uptask = new UploadTask();
uptask.execute(String.valueOf(finalJson));
我的 POST 异步任务如下:-
public class UploadTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
String JsonResponse = null;
String JsonDATA = params[0];
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://qftvufv4m1.execute-api.us-west-2.amazonaws.com/dev/OZCHHX");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
writer.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
Log.i("Response",JsonResponse);
return JsonResponse;
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("Error", "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
String status = null;
Log.d("Result",result);
if (pd != null)
{
pd.dismiss();
}
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
【问题讨论】:
-
这个请求在服务器中是什么样子的?你检查过日志吗?
-
你必须检查服务器是否接收到 JSON。现在你的问题看起来像
I have a backend problem, here is my client side code. How do I fix my backend? -
但是当我使用邮递员检查时,数据已输入数据库。我需要知道我的代码是否有任何错误。
标签: android json post android-asynctask httpurlconnection