Little coder
Little coder

Reputation: 13

Posting JSON to server using single string

I am posting data to server as single string. Its not posting. I am getting response.

I tried volley and retrofit. but I want to try in normal HTTP connection. I don't want to use other thing

    String api_url = "http://mywebsite.com/blah_blah";
  String book_now_request = "user_id=" + URLEncoder.encode(user_id, "UTF-8") + "&src=" + URLEncoder.encode(String.valueOf(src), "UTF-8") + "&src_lng=" + URLEncoder.encode(String.valueOf(src_lng) , "UTF-8" );



  JSONObject response_data = call_api(api_url, book_now_request);

  public JSONObject call_api(String api_url, String request_data) {
        try {
            URL url = new URL(api_url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));

            Log.e("request_data", request_data);

            writer.write(request_data);
            writer.flush();
            writer.close();
            os.close();

            BufferedReader bufferedReader = new BufferedReader(new    InputStreamReader(conn.getInputStream()));
            String line = "";
            String response = "";
            while ((line = bufferedReader.readLine()) != null) {
                response += line;
            }

            Log.d("API response", response);

            JSONObject response_data = new JSONObject(response);
            Log.e("J Response",response_data.toString());
            return response_data;

        } catch (Exception e) {
        //   Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
            Log.e("Exception", e.toString());
        }

        return null;
    }

Upvotes: 0

Views: 197

Answers (1)

Geek Boy
Geek Boy

Reputation: 30

I can understand your problem. Your passing it as raw data. You need to format it to JSON data.

String book_now_request = "{\"user_id\":\"key\",\"key\":\"value\",\"key\":\"value\"}"

Just try this. Hope this will work. Have a nice day!

Upvotes: 1

Related Questions