簡體   English   中英

我需要執行基本身份驗證以及將密鑰值作為 Http 發布請求的主體發送並獲取數據

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

url 的基本授權

正文 x-www-form-urlencoded 中的鍵值內容

我需要執行基本身份驗證並在正文中傳遞 www-form-urlencoded 數據。 我如何使用 http 在 java 中編碼,以獲取將上述數據傳遞給 url 后獲得的響應數據。

在我處理它之后,我得到了下面的代碼。

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);
}

我希望這對上述問題或上述代碼的優化有幫助並歡迎任何其他方法。

postman 可幫助您從自身創建代碼片段,您也可以使用它:

在此處輸入圖像描述

現在使用你想要的代碼:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM