如何将JSON对象作为正文发布?

时间:2017-07-27 06:57:53

标签: java android json post

我使用以下代码创建了JSON对象:

json = new JSONObject();
    try {
        json.put("success", true);
        JSONObject jCustomer = new JSONObject();
        jCustomer.put("LOGICALREF", 0);
        jCustomer.put("CODE", "");
        EditText definitionText = (EditText) findViewById(R.id.definitionText);
        jCustomer.put("DEFINITION_", definitionText.getText().toString());
        jCustomer.put("ISPERSCOMP", isPersComp);
        EditText taxOrIdNoText = (EditText) findViewById(R.id.taxOrIdNoText);
        if (isPersComp == 1){
            jCustomer.put("TAXNR", "");
            jCustomer.put("TCKNO", taxOrIdNoText.getText().toString());
        } else {
            jCustomer.put("TAXNR", taxOrIdNoText.getText().toString());
            jCustomer.put("TCKNO", "");
        }
        EditText taxOfficeText = (EditText) findViewById(R.id.taxOfficeText);
        String taxOfficeString = taxOfficeText.getText().toString();
        if (taxOfficeString.isEmpty() || taxOfficeString == null){
            jCustomer.put("TAXOFFICE", "TCKIMLIK");
        } else {
            jCustomer.put("TAXOFFICE", taxOfficeString);
        }
        EditText emailText = (EditText) findViewById(R.id.emailText);
        jCustomer.put("EMAILADDR", emailText.getText().toString());
        EditText address1Text = (EditText) findViewById(R.id.address1Text);
        jCustomer.put("ADDR1", address1Text.getText().toString());
        EditText address2Text = (EditText) findViewById(R.id.address2Text);
        jCustomer.put("ADDR2", address2Text.getText().toString());
        jCustomer.put("CITY", cityString);
        jCustomer.put("CITYCODE", cityNo);
        jCustomer.put("TOWN", townString);
        jCustomer.put("TOWNCODE", townNo);
        EditText inChargeText = (EditText) findViewById(R.id.inChargeText);
        jCustomer.put("INCHARGE", inChargeText.getText().toString());
        EditText nameText = (EditText) findViewById(R.id.nameText);
        jCustomer.put("NAME", nameText.getText().toString());
        EditText surnameText = (EditText) findViewById(R.id.surnameText);
        jCustomer.put("SURNAME", surnameText.getText().toString());
        EditText phoneNo1Text = (EditText) findViewById(R.id.phoneNo1Text);
        jCustomer.put("TELNRS1", phoneNo1Text.getText().toString());
        EditText phoneNo2Text = (EditText) findViewById(R.id.phoneNo2Text);
        jCustomer.put("TELNRS2", phoneNo2Text.getText().toString());
        json.put("data", jCustomer);
        new postJSON().execute();
    } catch (Exception e){
        e.printStackTrace();
    }

postJSON是一个扩展AsyncTask的私有类。这是它的代码:

private class postJSON extends AsyncTask<Void, Void, Void>{
    ProgressDialog progressDialog;

    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(NewCustomerInfoActivity.this);
        progressDialog.setMessage("Yeni müşteri kaydediliyor. Lütfen bekleyiniz.");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Don't know what to do here...
        return null;
    }

    protected void onPostExecute(Void requestResult) {
        super.onPostExecute(requestResult);
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }
}

现在我必须将它作为正文发布到服务器,我不知道从哪里开始。互联网上的大多数教程都使用我无法添加或找到的库,或者太复杂,我无法理解。我已经创建了一个webRequest函数,但是我使用它来从服务器获取JSON对象并且它可以工作:

public String getJson (String urlAdress, Boolean postRequest){
    URL url;
    String jString = "";
    try {
        url = new URL(urlAdress);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(15001);
        connection.setReadTimeout(15001);
        connection.setDoInput(true);
        if (postRequest){
            connection.setRequestMethod("POST");
        } else {
            connection.setRequestMethod("GET");
        }
        int requestResponse = connection.getResponseCode();
        if (requestResponse == HttpsURLConnection.HTTP_OK){
            String line;
            BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = buffer.readLine()) != null){
                jString += line;
            }
        } else {
            jString = "";
        }
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
    return jString;
}

如何将JSON对象作为正文添加到网址并发布?上述功能在发布时是否足够?

添加推荐代码后的编辑(输出流等):

服务器端的Web服务代码:

@RequestMapping(value = "/newCustomer", method = RequestMethod.POST, headers = "Accept=application/json; charset=utf-8", produces = "application/json")
private ResponseEntity<String> newCustomer (@RequestParam(value = "deviceId") String _deviceId,
              @RequestParam(value = "ssid") String _ssid,
              @RequestBody String _incomingData, //(value = "incomingData")
              HttpServletRequest _request,HttpServletResponse _response){
        Object responseMap = null;

        boolean response = false;
        System.out.println(_incomingData);

服务器的传入数据:

DEVICEID = ec5f501b01c54038&安培; SSID = QUCGFHA7ILIT3E9O8BHTD5NE4H&安培;%7B%22success%22%3Atrue%2C%22data%22%3A%7B%22LOGICALREF%22%3A0%2C%22CODE%22%3A%22%22%2C% 22DEFINITION_%22%3A%22asdasd%22%2C%22ISPERSCOMP%22%3A0%2C%22TAXNR%22%3A%22564564%22%2C%22TCKNO%22%3A%22%22%2C%22TAXOFFICE%22%3A% 22ghfgh%22%2C%22EMAILADDR%22%3A%22asdasd%22%2C%22ADDR1%22%3A%22asdas%22%2C%22ADDR2%22%3A%22asdasd%22%2C%22CITY%22%3A%22Amasya% 22%2C%22CITYCODE%22%3A5%2C%22TOWN%22%3A%22Hamam%C3%83%C2%B6z%C3%83%C2%BC%22%2C%22TOWNCODE%22%3A3%2C%22INCHARGE% 22%3A%22xcvxcb%22%2C%22NAME%22%3A%22xcbxcb%22%2C%22SURNAME%22%3A%22gxcb%22%2C%22TELNRS1%22%3A%22456456%22%2C%22TELNRS2%22% 3A%225456456%22%7D%7D =

ssId和deviceId不应该作为身体的一部分发送。然而就是这样。

我目前使用的功能:

public String postJson (String urlAdress, Boolean postRequest, JSONObject json){
    URL url;
    String jString = "";
    try {
        url = new URL(urlAdress);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(15001);
        connection.setReadTimeout(15001);
        connection.setDoInput(true);
        if (postRequest){
            connection.setRequestMethod("POST");
        } else {
            connection.setRequestMethod("GET");
        }
        connection.connect();
        OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
        request.write(json.toString());
        request.flush();
        int requestResponse = connection.getResponseCode();
        if (requestResponse == HttpsURLConnection.HTTP_OK){

        } else {
            jString = "";
        }
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
    return jString;
}

2 个答案:

答案 0 :(得分:3)

connection.setDoOutput(true);下方添加行connection.setDoInput(true);

然后从outputStream获取HttpURLConnection并在那里写json,如下所示:

   OutputStream os = connection.getOutputStream();
   os.write(json.toString().getBytes("UTF-8"));
   os.close();

答案 1 :(得分:-2)

使用Retrofit,

博客 - https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

图书馆 - http://square.github.io/retrofit

使用POON的POJO类很容易实现。

没有外部库,

试试这个,

public static String POST(Activity context, String connectionURL,
                          YOURBODYOBJECT mparms) throws Exception {

    try {
        url = new URL(connectionURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(30000);
        connection.setConnectTimeout(30000);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded"); // Change header for your convience.
        connection.setChunkedStreamingMode(0);
        connection.setRequestMethod("POST");
        connection.connect();
        request = new OutputStreamWriter(connection.getOutputStream());
        request.write(mparms);// pass your body content
        request.flush();
        HTTP_RESPONSE_CODE = connection.getResponseCode();
        switch (HTTP_RESPONSE_CODE) {
            case HttpURLConnection.HTTP_OK:
                isr = new InputStreamReader(connection.getInputStream());
                reader = new BufferedReader(isr);
                sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                // response variable.
                response = sb.toString();
                isr.close();
                reader.close();
                return response.trim();

            case HttpURLConnection.HTTP_UNAUTHORIZED:
                return String.valueOf(HTTP_RESPONSE_CODE).trim();

            case HttpURLConnection.HTTP_BAD_REQUEST:
                isr = new InputStreamReader(connection.getErrorStream());
                reader = new BufferedReader(isr);
                sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                response = sb.toString();
                isr.close();
                reader.close();
                return response.trim();

            case HttpURLConnection.HTTP_INTERNAL_ERROR:
                isr = new InputStreamReader(connection.getErrorStream());
                reader = new BufferedReader(isr);
                sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                response = sb.toString();
                isr.close();
                reader.close();
                return response.trim();

            default:
                return response.trim();
        }

    } catch (Exception e) {
        // Error
        return e.getMessage();

    } finally {
        connection.disconnect();
    }
}