Connecting to remote URL which requires authentication using Java

前端 未结 12 2183
庸人自扰
庸人自扰 2020-11-22 12:59

How do I connect to a remote URL in Java which requires authentication. I\'m trying to find a way to modify the following code to be able to programatically provide a userna

12条回答
  •  攒了一身酷
    2020-11-22 13:41

    i did that this way you need to do this just copy paste it be happy

        HttpURLConnection urlConnection;
        String url;
     //   String data = json;
        String result = null;
        try {
            String username ="danish.hussain@gmail.com";
            String password = "12345678";
    
            String auth =new String(username + ":" + password);
            byte[] data1 = auth.getBytes(UTF_8);
            String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
            //Connect
            urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Authorization", "Basic "+base64);
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(10000);
            urlConnection.connect();
            JSONObject obj = new JSONObject();
    
            obj.put("MobileNumber", "+97333746934");
            obj.put("EmailAddress", "danish.hussain@mee.com");
            obj.put("FirstName", "Danish");
            obj.put("LastName", "Hussain");
            obj.put("Country", "BH");
            obj.put("Language", "EN");
            String data = obj.toString();
            //Write
            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();
            int responseCode=urlConnection.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                //Read
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
    
            String line = null;
            StringBuilder sb = new StringBuilder();
    
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
    
            bufferedReader.close();
            result = sb.toString();
    
            }else {
            //    return new String("false : "+responseCode);
            new String("false : "+responseCode);
            }
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

提交回复
热议问题