Java访问用户名密码验证的url
生活随笔
收集整理的這篇文章主要介紹了
Java访问用户名密码验证的url
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java訪問用戶名密碼驗證的url
- 引言
- 代碼解釋
引言
有些url帶有用戶名密碼,我們直接用curl或者wget訪問的時候出現401,沒有訪問權限。這時我們就需要對url進行必要的權限處理
代碼解釋
private static String Post1(String url, String hexString) throws IOException {CloseableHttpClient client = HttpClients.createDefault();HttpPost get = new HttpPost(url);StringEntity stringEntity = new StringEntity("json="+hexString);stringEntity.setContentType("application/x-www-form-urlencoded");get.setEntity(stringEntity);ProtocolVersion protocolVersion = get.getProtocolVersion();System.out.println(protocolVersion.getProtocol());try {//該網頁需要認證(用戶名、密碼)HttpClientContext context = new HttpClientContext();CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));context.setCredentialsProvider(credentialsProvider);CloseableHttpResponse execute = client.execute(get, context);//----以下一樣HttpEntity entity = execute.getEntity();InputStream in = entity.getContent();StringBuilder builder = new StringBuilder();BufferedReader bufreader = new BufferedReader(new InputStreamReader(in));for (String temp = bufreader.readLine(); temp != null; temp = bufreader.readLine()) {builder.append(temp);}return builder.toString();} catch (ClientProtocolException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);} }總結
以上是生活随笔為你收集整理的Java访问用户名密码验证的url的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式之-生成器模式
- 下一篇: 最好用的音轨分离软件spleeter:处