使用HttpURLConnection在android

时间:2019-01-23 04:34:11

标签: android json rest android-asynctask

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

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

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;
}
}

3 个答案:

答案 0 :(得分:0)

尝试一下:

 OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(jsonArrayToPost.toString());

答案 1 :(得分:0)

您可以将inputStream设置为String:

private String getContent(InputStream inputStream) {
    //将流转换为Stirng ; change to String

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder sb = new StringBuilder();

    String line = null;
    try{
        while ((line = reader.readLine()) != null){
            sb.append(line+ "/n");
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return sb.toString();
}

答案 2 :(得分:0)

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