0

I'm currently working on an HTTP Request and it worked pretty good so far, now there is an Authentication Window and I'd like to know how to pass Username and Password without adding an external jar like the Appache HTTP Client.

The Basic Authentication with

username:password@exampleUrl.com didn't work.

My Code so far:

private String[][] content;

public String[][] sendRequest(String urlPart) {

    try {

        String url = "http://exampleurl.com"+urlPart; 

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();


        //convert response 
        JSONObject myresponse = new JSONObject(response.toString());
        JSONObject d_object = new JSONObject(myresponse.getJSONObject("d").toString());
        JSONArray results = new JSONArray(d_object.getJSONArray("results").toString());

        content = new String[results.length()][2];

        for (int i = 0; i < results.length(); i++) 
        {

            JSONObject stereo = results.getJSONObject(i);
            content[i][0] = stereo.getString("RET_NAME");
            content[i][1] = stereo.getString("RET_VALUE");
        }

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

    return content;
}

enter image description here

Nihal
  • 5,262
  • 7
  • 23
  • 41
PetPat
  • 1
  • 2

2 Answers2

0

Looks like Basic Authentication. The credentials will be sent with an "Authorization" Header. So, technically, you would need to work with those headers, if you don't want to use other convenience options. (like HTTP Client)

Mick
  • 954
  • 7
  • 17
0

You may find some solution here: Http Basic Authentication in Java using HttpClient

You need "DefaultHttpClient" and set "Credential" for the authentication and post is.

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
        new UsernamePasswordCredentials("test1", "test1"));
HttpPost httppost = new HttpPost("http://host:post/test/login");

HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

And after it you can get the response. I hope this will helpful.

DiabloSteve
  • 431
  • 2
  • 13