1

I'm using an url in order to read json data but it doesn't work because there is an authentication requested to get access to it using only the username (no login, no password only username). so my code show me the error :

java.io.IOException: Server returned HTTP response code: 401 for URL

My code is working using another URL with no authentication.

Could someone help me or give me and example that do the same thing.

many thanks to you in advance

package javaapplication3;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    import java.net.URLConnection;
    import java.nio.charset.Charset;

    import org.json.JSONArray;
    import org.json.JSONException;

    public class JSONREST {

        public static String callURL(String myURL) {
            System.out.println("Requested URL:" + myURL);
            StringBuilder sb = new StringBuilder();
            URLConnection urlConn = null;
            InputStreamReader in = null;
            try {
                URL url = new URL(myURL);
                urlConn = url.openConnection();
                if (urlConn != null) {
                    urlConn.setReadTimeout(60 * 1000);
                }
                if (urlConn != null && urlConn.getInputStream() != null) {
                    in = new InputStreamReader(urlConn.getInputStream(),
                            Charset.defaultCharset());
                    BufferedReader bufferedReader = new BufferedReader(in);
                    if (bufferedReader != null) {
                        int cp;
                        while ((cp = bufferedReader.read()) != -1) {
                            sb.append((char) cp);
                        }
                        bufferedReader.close();
                    }
                }
                in.close();
            } catch (Exception e) {
                throw new RuntimeException("Exception while calling URL:" + myURL, e);
            }

            return sb.toString();
        }

        public static void main(String[] args) {

            String jsonString = callURL("MY URL");
            System.out.println("\n\njsonString: " + jsonString);

            try {
                JSONArray jsonArray = new JSONArray(jsonString);
                System.out.println("\n\njsonArray: " + jsonArray);
            } 
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }
Carl Bo
  • 13
  • 3

0 Answers0