zoukankan      html  css  js  c++  java
  • Java Server returned HTTP response code: 401

    今天写一个小功能需要通过http请求获取一些返回数据,但是在登陆时是需要进行用户名和密码的校验的。写好之后请求,返回异常Java Server returned HTTP response code: 401

    下面是修改之后的代码:

     1 private static void httpRequest(){
     2          String username = "XX";
     3          String password = "XX";
     4          String requestURL = "https://XXXX";
     5          
     6          URL url;
     7          URLConnection connection = null;
     8          try {
     9              url = new URL(requestURL);
    10              connection = (HttpURLConnection) url.openConnection();
    11              String encoding = new String(Base64.encode(new String(username+":"+password).getBytes()));
    12              ((HttpURLConnection) connection).setRequestMethod("GET");
    13              connection.setRequestProperty("Content-Type", "text/plain");
    14              connection.setRequestProperty("charset", "UTF-8");
    15              connection.setRequestProperty( "Authorization","Basic "+encoding); 
    16              connection.connect();
    17              
    18              BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
    19              File fp = new File("/tmp/xml.txt");// 获取整个返回的结果入/tmp/xml.txt中
    20              PrintWriter pfp= new PrintWriter(fp);
    21              pfp.print(in.readLine());// 返回结果只有一行……
    22         pfp.close(); 
    23 
    24         in.close(); 
    25 
    26       } catch (MalformedURLException e) { 
    27 
    28          // TODO Auto-generated catch block 
    29          e.printStackTrace();
    30       } catch (IOException e) {
    31         // TODO Auto-generated catch block
    32          e.printStackTrace(); 
    33       }finally{ 
    34       }
    35      }

    注意事项:

    1. 第15行,Basic 后面有一个空格

    参考:http://stackoverflow.com/questions/22677930/java-server-returned-http-response-code-401

  • 相关阅读:
    终于合一起了...
    关于Earley第二篇论文给的建立parse tree的算法的bug
    不作恶
    windows server安装ATI显卡驱动
    不作恶:这次我是一个坚定的五毛党
    看了老刘的文章
    webkit svg高斯模糊的bug
    世界不平坦
    我发现我对人类活动的认识开始有一点点变化了
    css parsing中词法的RegEx(python)
  • 原文地址:https://www.cnblogs.com/fengxm/p/4071718.html
Copyright © 2011-2022 走看看