-3

I am quite new to json Handling with Java API

I want to Pass ID and Password to server and want to retrieve Data related to that ID.I m using Java API file to send data instead of PHP Files.

Here is my code:

To read .Json file from Assets

    public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("auth.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

Function to attach parameter values to json file

public void save() {
    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        //JSONArray arr = obj.getJSONArray("");
        username = etUsername.getText().toString().trim();
        password = etPassword.getText().toString().trim();
        obj.put("sso_id", username);
        obj.put("password", password);

        jsonArray.put(obj);
        Log.v("AUTHENTICATE", "Data is " + jsonArray.toString());
        JSONObject response;
        try {
            Log.v("AUTHENTICATE", jsonArray.toString());
            //response = helper.sendJsonData(jsonArray.toString(),GET_DATA ) ;
            new SendDataToServer().execute(String.valueOf(obj));
            //new GetData().execute();
            //Log.v("AUTHENTICATE", "Response is " + response.toString());
        } catch (Exception e) {
            Log.v("AUTHENTICATE", "Exception in response  is " + e.toString());
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }


}

AsyncTask code to call Url

String JsonResponse = null;
        String JsonDATA = params[0];
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(GET_DATA);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            // is output buffer writter
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            //urlConnection.setRequestProperty("Accept", "*/*");
            //set headers and method
            Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            writer.write(JsonDATA);
            // json data
            writer.close();
            InputStream inputStream = urlConnection.getInputStream();
            //input stream
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String inputLine;
            while ((inputLine = reader.readLine()) != null)
                buffer.append(inputLine + "\n");
            if (buffer.length() == 0) {
                // Stream was empty. No point in parsing.
                return null;
            }
            JsonResponse = buffer.toString();
            //response data
            Log.i("AUTHENTICATE", JsonResponse);
            //send to post execute
            return JsonResponse;


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("AUTHENTICATE", "Error closing stream", e);
                }
            }
        }
        return null;

}

.json File

{"sso_id":"",
 "password":""}

giving me Exception

java.io.FileNotFoundException: http://example.com/user/auth

on below Line in Async Task

InputStream inputStream = urlConnection.getInputStream();

What will be the issue??

Pranita
  • 784
  • 6
  • 15

1 Answers1

0

Use java.net.URL#openStream() with a proper URL (including the protocol!). E.g.

InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();

How can you use the same request object POST for both writing and reading data? It cannot be used for reading the data! Change it to GET.

Also, you need to change to urlConnection.setDoOutput(false);

Aakash Verma
  • 2,459
  • 1
  • 18
  • 45
  • not working..its giving me UnknownHostException.also tried using GET Method and urlConnection.setDoOutput(false); but not working in either case – Pranita Jun 29 '17 at 11:17
  • I hope you're using GET_DATA and not "http://www.somewebsite.com/a.txt" :D – Aakash Verma Jun 29 '17 at 11:20
  • GET_DATA is Constant String value which is myDomainName(Here example.com) " example.com/user/auth " – Pranita Jun 29 '17 at 11:38
  • I know that.I just thought you were using the URL that I gave you. Apart from that, I believe you should use the URL freshly and not just modify its fields. Look [here](https://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests) – Aakash Verma Jun 29 '17 at 11:52