使用HttpURLConnection在android中发送JSON发布请求 [英] Using HttpURLConnection to send a JSON post request in android

查看:155
本文介绍了使用HttpURLConnection在android中发送JSON发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发的新手,我正在尝试使用HttpURLConnection发送带有JSON正文的发布请求.使用Postman或python可以成功将数据发布到其余的api,但是由于某种原因,即使我没有收到任何错误,我也无法在android studio中发布JSON数组...服务器实际上返回true(应该发生这种情况),我认为正在建立连接(我得到200个响应代码),但发布JSON从未发生.

I'm new to Android development and I'm trying to send a post request with a JSON body using HttpURLConnection. Using Postman or python will successfully post the data to the rest api, but for some reason i'm unable to post the JSON Array in android studio even though I get no errors... The server actually returns true(Which is supposed to happen) which I think that the connection is being made (i'm getting 200 response code) but posting the JSON never happens.

有人可以帮助我确定帖子是否发布到api上吗?非常感谢

Would someone be able to help me find out if the post makes it to the api? It would be much appreciated

JSON格式:

 [   {
    "timeOfEvent": "2019-01-23T02:00:56",
    "incidentId": 473,
    "description": "testing tweet #4",
    "incidentTypeId": 1,
    "source": "Twitter",
    "user": null,
    "url": null,
    "sourceId": "1087892909335199745"   } ]

public class postJsonTask extends AsyncTask<String,String,JSONObject> {

@Override
protected JSONObject doInBackground(String... params){

    Log.i("postJSONTask","Beginning of doInBackGround");
    JSONObject jsonToPost = new JSONObject();
    JSONArray jsonArrayToPost = new JSONArray();
    HttpURLConnection conn = null;

    try {
        URL url = new URL("my url goes here");
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15*1000);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();

        jsonToPost.put("timeOfEvent", "2019-01-21T09:10:10");
        jsonToPost.put("incidentId", 1);
        jsonToPost.put("description", "Ayman Testing data");
        jsonToPost.put("incidentTypeId", 1);
        jsonToPost.put("source", null);
        jsonToPost.put("user", null);
        jsonToPost.put("url", null);
        jsonToPost.put("sourceId", null);
        jsonArrayToPost.put(jsonToPost);

        OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
        Log.i("postJSONTask","Conn.getOutputStream "+ conn.getOutputStream().toString());
        Log.i("postJSONTask","Trying to post: "+ jsonArrayToPost.toString());


        streamWriter.write(jsonArrayToPost.toString());
        streamWriter.flush();
        streamWriter.close();

        StringBuilder stringBuilder = new StringBuilder();
        Log.i("postJSONTask, message",conn.getResponseMessage());
        Log.i("postJSONTask respoCode", String.valueOf(conn.getResponseCode()));

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

            InputStreamReader streamReader = new InputStreamReader(conn.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(streamReader);
            String response = null;

            while ((response = bufferedReader.readLine()) != null) {
                stringBuilder.append(response + "\n");
            }
            bufferedReader.close();
            Log.d("postJSONTask response", stringBuilder.toString());

        } else {
            Log.e("postJSONTask error", conn.getResponseMessage());
            return null;
        }
    } catch (Exception e) {
        Log.e("postJsonTask error", e.toString());
        return null;

    }
    finally{
        conn.disconnect();
    }


    return null;
}
}

推荐答案

在能够建立rest-api的同事的帮助下,我能够指出问题出在哪里.我的JSON数组的参数错误,我不得不删除IncidentId ...谢谢大家的帮助!

I was able to point out where the problem was with the help of my colleague who worked on setting up the rest-api. The parameters of my JSON array were wrong and I had to remove the IncidentId... Thank you all for your help!

这篇关于使用HttpURLConnection在android中发送JSON发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆