簡體   English   中英

使用HttpURLConnection在android中發送JSON發布請求

[英]Using HttpURLConnection to send a JSON post request in android

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

嘗試這個:

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

您可以將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();
}

在能夠建立rest-api的同事的幫助下,我能夠指出問題出在哪里。 我的JSON數組的參數錯誤,我不得不刪除IncidentId ...謝謝大家的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM