Using HTTP Basic-Auth with Google App Engine URLFetch service

后端 未结 6 618
眼角桃花
眼角桃花 2020-12-07 23:01

How can I specify the username and password for making Basic-Auth requests with App Engine\'s URLFetch service (in Java)?

It seems I can set HTTP headers:

         


        
6条回答
  •  一个人的身影
    2020-12-07 23:47

    Using HttpURLConnection gave me some problems (for some reason the server I was trying to connect to didn't accept auth credentials), and finally I realized that it's actually much easier to do using GAE's low-level URLFetch API (com.google.appengine.api.urlfetch) like so:

    URL fetchurl = new URL(url);
    
    String nameAndPassword = credentials.get("name")+":"+credentials.get("password");
    String authorizationString = "Basic " + Base64.encode(nameAndPassword.getBytes());
    
    HTTPRequest request = new HTTPRequest(fetchurl);
    request.addHeader(new HTTPHeader("Authorization", authorizationString));
    
    HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
    System.out.println(new String(response.getContent()));
    

    This worked.

提交回复
热议问题