I need to perform Basic authentication as well as send key value as body for a Http Post request and get data

730 views Asked by At

Basic Authorization for url

Key value content in body x-www-form-urlencoded

I need to perform both basic auth and pass www-form-urlencoded data in the body. How can i code in java using http to get response data obtained after passing above data to the url.

2

There are 2 answers

0
Prajwal Jm On BEST ANSWER

After I worked on it I got the below code which works.

public void postMethod() throws Exception{
    String result="";
    try{
        Map<String,String> map=new LinkedHashMap<>();
        map.put("key_data","value");
        StringBuilder postdata=new StringBuilder();
        for(Map.Entry<String,String> param:map.entrySet()){
            if(postdata.length()!=0) postdata.append('&');
            postdata.append(URLEncoder.encode(param.getKey(),"UTF-8"));
            postdata.append('=');
            postdata.append(URLEncoder.encode(param.getValue(),"UTF-8"));
        }
        byte[] data=postdata.toString().getBytes("UTF-8");
        String user='admin';
        String pwd='admin';
        String val=user+":"+pwd;
        String url="https://example.com";
        byte[] authEncode=Base64.encodeBase64(val.getBytes());
        String authString=new String(authEncoder);
        URL url1=new URL(url);
        HttpURLConnection urlConnection=(HttpURLConnection)url1.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Authorization","Basic "+authString);
        urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("Content-Length",String.valueOf(data.length));
        urlConnection.setDoOutput(true);
        urlConnection.getOutputStream().write(data);
        Reader in=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
        StringBuilder str=new StringBuilder();
        for(int i;(i=in.read())>=0;)
            str.append((char)i);
        result=str.toString();
    }
    catch(Exception e){
    //handle the exception
    }
    System.out.println(result);
}

I hope this helps and welcome any other method for the above question or optimization of the above code.

0
PDHide On

postman helps you create code snippet from itself you can use that also:

enter image description here

Now use the code you want :

enter image description here