2012-04-04 17 views
9

मैं अपाचे HttpComponents का उपयोग एक वेब सेवा का उपयोग करने के लिए, और डॉन 'पता है कि अनुरोध में उपयोगकर्ता/पासवर्ड सेट करने के लिए, यहाँ मेरी कोड है स्थापित करने के लिए:कैसे उपयोगकर्ता नाम/httpget में पासवर्ड

URI url = new URI(query); 
HttpGet httpget = new HttpGet(url); 

DefaultHttpClient httpclient = new DefaultHttpClient(); 
Credentials defaultcreds = new UsernamePasswordCredentials("test", "test"); 
httpclient.getCredentialsProvider().setCredentials(new AuthScope(HOST, AuthScope.ANY_PORT), defaultcreds); 

HttpResponse response = httpclient.execute(httpget); 

..

लेकिन फिर भी इसे 401 अनधिकृत त्रुटि मिली।

HTTP/1.1 401 Unauthorized [Server: Apache-Coyote/1.1, Pragma: No-cache, Cache-Control: no-cache, Expires: Wed, 31 Dec 1969 16:00:00 PST, WWW-Authenticate: Basic realm="MemoryRealm", Content-Type: text/html;charset=utf-8, Content-Length: 954, Date: Wed, 04 Apr 2012 02:28:49 GMT] 

मुझे यकीन नहीं है कि यह उपयोगकर्ता/पासवर्ड सेट करने का सही तरीका है या नहीं? कोई भी मदद कर सकता है? धन्यवाद।

उत्तर

4

मुझे लगता है कि आप सही रास्ते पर हैं। शायद आपको अपने उपयोगकर्ता प्रमाण पत्र को http error response के रूप में जांचना चाहिए, शायद गलत उपयोगकर्ता नाम/पासवर्ड का अर्थ हो सकता है या उपयोगकर्ता को संसाधनों तक पहुंचने का विशेषाधिकार नहीं है। मेरे पास निम्न कोड है जो मैं मूल http प्रमाणीकरण करता हूं और यह ठीक काम कर रहा है।

import org.apache.http.HttpResponse; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 


public class Authentication 
{ 

    public static void main(String[] args) 
    { 

     DefaultHttpClient dhttpclient = new DefaultHttpClient(); 

     String username = "abc"; 
     String password = "def"; 
     String host = "abc.example.com"; 
     String uri = "http://abc.example.com/protected"; 

     try 
     { 
      dhttpclient.getCredentialsProvider().setCredentials(new AuthScope(host, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); 
      HttpGet dhttpget = new HttpGet(uri); 

      System.out.println("executing request " + dhttpget.getRequestLine()); 
      HttpResponse dresponse = dhttpclient.execute(dhttpget); 

      System.out.println(dresponse.getStatusLine() ); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      dhttpclient.getConnectionManager().shutdown(); 
     } 

    } 

} 
संबंधित मुद्दे