2010-07-19 31 views
101

मैं जावा में इस कर्ल आदेश की कार्यक्षमता की नकल करने की कोशिश कर रहा हूँ:एचटीपी क्लाइंट का उपयोग कर जावा में एचटीपी मूल प्रमाणीकरण?

curl --basic --user username:password -d "" http://ipaddress/test/login 

मैं निम्नलिखित का उपयोग कर कॉमन्स HttpClient 3.0 लिखा था लेकिन किसी भी तरह सर्वर से एक 500 Internal Server Error हो रही समाप्त हो गया। क्या कोई मुझे बता सकता है कि मैं कुछ गलत कर रहा हूं?

public class HttpBasicAuth { 

    private static final String ENCODING = "UTF-8"; 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     try { 

      HttpClient client = new HttpClient(); 

      client.getState().setCredentials(
        new AuthScope("ipaddress", 443, "realm"), 
        new UsernamePasswordCredentials("test1", "test1") 
        ); 

      PostMethod post = new PostMethod(
        "http://address/test/login"); 

      post.setDoAuthentication(true); 

      try { 
       int status = client.executeMethod(post); 
       System.out.println(status + "\n" + post.getResponseBodyAsString()); 
      } finally { 
       // release any connection resources used by the method 
       post.releaseConnection(); 
      } 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
    } 

और मैं बाद में करने की कोशिश की एक कॉमन्स HttpClient 4.0.1 लेकिन अब भी वही त्रुटि:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 


public class HttpBasicAuth { 

    private static final String ENCODING = "UTF-8"; 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     try { 
      DefaultHttpClient httpclient = new DefaultHttpClient(); 

      httpclient.getCredentialsProvider().setCredentials(
        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
        new UsernamePasswordCredentials("test1", "test1")); 

      HttpPost httppost = new HttpPost("http://host:post/test/login"); 

      System.out.println("executing request " + httppost.getRequestLine()); 
      HttpResponse response; 
      response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 

      System.out.println("----------------------------------------"); 
      System.out.println(response.getStatusLine()); 
      if (entity != null) { 
       System.out.println("Response content length: " + entity.getContentLength()); 
      } 
      if (entity != null) { 
       entity.consumeContent(); 
      } 

      httpclient.getConnectionManager().shutdown(); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
} 
+0

उम का उपयोग करते समय क्या सर्वर लॉग में दिखाने त्रुटि? – hvgotcodes

+0

आह ... मेरे पास सर्वर लॉग तक पहुंच नहीं है :( – Legend

+0

अधिकांश समय प्राधिकरण कुंजी का उपयोग हम कर रहे हैं गलत हो सकता है। http://dev.tapjoy.com/faq/how-to- find-sender-id-and-api-key-for-gcm/यह देखने के लिए कि आप सही कुंजी का उपयोग कर रहे हैं या नहीं। फायरबेस के लिए API कुंजी का चयन करते समय भी मुझे भ्रमित हो गया है हमें क्लाउड में SENDER ID - API कुंजी जोड़ी का उपयोग करना होगा firebase सेटिंग के अंतर्गत मैसेजिंग टैब यानी जाओ अनुप्रयोग firebase करने के लिए -।> एप्लिकेशन सेटिंग में जाएं -।> क्लाउड संदेश वहाँ आप पा सकते हैं प्रेषक आईडी <==> API कुंजी और इस API कुंजी आप FCM भेजने के लिए उपयोग कर सकते हैं – Rahul

उत्तर

74

ठीक है तो यह एक काम करता है। बस में मामला किसी को भी यह चाहता है, यहाँ संस्करण है कि मेरे लिए :)

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.Base64; 


public class HttpBasicAuth { 

    public static void main(String[] args) { 

     try { 
      URL url = new URL ("http://ip:port/login"); 
      String encoding = Base64.getEncoder().encodeToString(("test1:test1").getBytes(‌"UTF‌​-8"​)); 

      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("POST"); 
      connection.setDoOutput(true); 
      connection.setRequestProperty ("Authorization", "Basic " + encoding); 
      InputStream content = (InputStream)connection.getInputStream(); 
      BufferedReader in = 
       new BufferedReader (new InputStreamReader (content)); 
      String line; 
      while ((line = in.readLine()) != null) { 
       System.out.println(line); 
      } 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 

    } 

} 
+17

जहां कर सकते हैं मुझे बेस 64 एन्कोडर मिल गया है? –

+2

@ मुहन्नाद अपाचे कॉमन्स कोडेक –

+4

'बेस 64 एन्कोडर' नहीं मिला। जोनास आप याचिका कर सकते हैं से पूरा जार देना? 'Base64Encoder' का पूर्णतः योग्य वर्ग नाम क्या है? – Jus12

7

यहाँ कुछ बातें बताई गई हैं काम करता है:

  • यदि आप कर सकते हैं, HttpClient 4 के उन्नयन (आम तौर पर बोल रहा विचार कर सकते हैं , मुझे नहीं लगता कि संस्करण 3 अभी भी सक्रिय रूप से समर्थित है)।

  • एक 500 स्थिति कोड एक सर्वर त्रुटि है, इसलिए यह देखने के लिए उपयोगी हो सकता है कि सर्वर क्या कहता है (प्रतिक्रिया शरीर में कोई संकेत जो आप प्रिंट कर रहे हैं?)। यद्यपि यह आपके क्लाइंट के कारण हो सकता है, सर्वर इस तरह विफल नहीं होना चाहिए (अनुरोध गलत होने पर 4xx त्रुटि कोड अधिक उपयुक्त होगा)।

  • मुझे लगता है कि setDoAuthentication(true) डिफ़ॉल्ट है (सुनिश्चित नहीं है)। क्या प्रयास करने के लिए उपयोगी हो सकता है पूर्व रिक्तिपूर्व प्रमाणीकरण काम करता है बेहतर:

    client.getParams().setAuthenticationPreemptive(true); 
    

अन्यथा, curl -d "" और क्या आप जावा में कर रहे हैं के बीच मुख्य अंतर यह है कि, Content-Length: 0 के अलावा, कर्ल भी भेजता है Content-Type: application/x-www-form-urlencoded। ध्यान दें कि डिज़ाइन के संदर्भ में, आपको शायद अपने POST अनुरोध के साथ एक इकाई भेजनी चाहिए।

125

आप इस की कोशिश की है (का उपयोग कर HttpClient संस्करण 4)

String encoding = Base64Encoder.encode ("test1:test1"); 
HttpPost httppost = new HttpPost("http://host:post/test/login"); 
httppost.setHeader("Authorization", "Basic " + encoding); 

System.out.println("executing request " + httppost.getRequestLine()); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity entity = response.getEntity(); 
+1

किस लाइब्रेरी में Base64Encoder उपलब्ध है? –

+1

'sun.misc.Base64Encoder'। –

+20

जावा 8 के रूप में 'java.util.Base64' का उपयोग करने के लिए बेहतर: 'Base64.getEncoder()। EncodeToString ((" test1: test1 ")। GetBytes());' – berry120

13

एक छोटा सा अद्यतन - किसी के लिए उम्मीद है कि उपयोगी है - यह अपने प्रोजेक्ट में मेरे लिए काम करता है:

  • मैं अच्छा लोक का उपयोग रॉबर्ट हार्डर से डोमेन क्लास बेस 64.जावा (धन्यवाद रॉबर्ट - कोड यहां उपलब्ध है: Base64 - डाउनलोड करें और इसे अपने पैकेज में रखें)।

  • और फ़ाइल (छवि, दस्तावेज़ इत्यादि) का डाउनलोड करें।) प्रमाणीकरण के साथ और स्थानीय डिस्क

उदाहरण के लिए लिखें: Maven निर्भरता

import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

public class HttpBasicAuth { 

public static void downloadFileWithAuth(String urlStr, String user, String pass, String outFilePath) { 
    try { 
     // URL url = new URL ("http://ip:port/download_url"); 
     URL url = new URL(urlStr); 
     String authStr = user + ":" + pass; 
     String authEncoded = Base64.encodeBytes(authStr.getBytes()); 

     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("GET"); 
     connection.setDoOutput(true); 
     connection.setRequestProperty("Authorization", "Basic " + authEncoded); 

     File file = new File(outFilePath); 
     InputStream in = (InputStream) connection.getInputStream(); 
     OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); 
     for (int b; (b = in.read()) != -1;) { 
      out.write(b); 
     } 
     out.close(); 
     in.close(); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 
+2

मुझे मिलता है 'विधि एन्कोडबाइट्स (बाइट []) बेस 64' –

+0

के लिए अपरिभाषित है कस्टम बेस 64 वर्ग को' import org.apache.commons.codec.binary.Base64; 'के रूप में [इस पृष्ठ पर इस उत्तर में विस्तृत] [http://stackoverflow.com/a/24618341/26510) –

+2

जावा 8 में, आप इसका उपयोग कर सकते हैं: import java.util.Base64; –

2

HttpBasicAuth छोटे परिवर्तन के साथ मेरे लिए काम करता

  1. मैं उपयोग

    <dependency> 
        <groupId>net.iharder</groupId> 
        <artifactId>base64</artifactId> 
        <version>2.3.8</version> 
    </dependency> 
    
  2. समाल ler उदाहरण के लिए

    String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes()); 
    
3
HttpClient हमेशा उपयोग HttpRequestInterceptor के लिए

बदलने

httclient.addRequestInterceptor(new HttpRequestInterceptor() { 
    public void process(HttpRequest arg0, HttpContext context) throws HttpException, IOException { 
     AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); 
     if (state.getAuthScheme() == null) { 
      BasicScheme scheme = new BasicScheme(); 
      CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); 
      Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY); 
      if (credentials == null) { 
       System.out.println("Credential >>" + credentials); 
       throw new HttpException(); 
      } 
      state.setAuthScope(AuthScope.ANY); 
      state.setAuthScheme(scheme); 
      state.setCredentials(credentials); 
     } 
    } 
}, 0); 
4

ऊपर सभी प्रश्नों के उत्तर के लिए धन्यवाद, लेकिन मेरे लिए, मैं Base64Encoder वर्ग नहीं मिल रहा है, तो मैं तरह बाहर मेरे रास्ते वैसे भी।

public static void main(String[] args) { 
    try { 
     DefaultHttpClient Client = new DefaultHttpClient(); 

     HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd"); 
     String encoding = DatatypeConverter.printBase64Binary("user:passwd".getBytes("UTF-8")); 
     httpGet.setHeader("Authorization", "Basic " + encoding); 

     HttpResponse response = Client.execute(httpGet); 

     System.out.println("response = " + response); 

     BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     StringBuilder responseString = new StringBuilder(); 
     String line = ""; 
     while ((line = breader.readLine()) != null) { 
      responseString.append(line); 
     } 
     breader.close(); 
     String repsonseStr = responseString.toString(); 

     System.out.println("repsonseStr = " + repsonseStr); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

एक और बात, मैं भी कोशिश की

Base64.encodeBase64String("user:passwd".getBytes()); 

यह काम नहीं करता यह की वजह से एक स्ट्रिंग

DatatypeConverter.printBase64Binary() 

साथ लगभग एक ही लौट लेकिन साथ "\ r \ n" अंत , तो सर्वर "खराब अनुरोध" वापस करेगा।

इसके अलावा कोड भी काम कर रहा है, वास्तव में मैं इसे पहले हल करता हूं, लेकिन किसी कारण से, यह कुछ क्लाउड वातावरण में काम नहीं करता है (sae.sina.com.cn अगर आप जानना चाहते हैं, तो यह एक चीनी है क्लाउड सेवा)। इसलिए HttpClient प्रमाण-पत्रों के बजाय http शीर्षलेख का उपयोग करना होगा।

public static void main(String[] args) { 
    try { 
     DefaultHttpClient Client = new DefaultHttpClient(); 
     Client.getCredentialsProvider().setCredentials(
       AuthScope.ANY, 
       new UsernamePasswordCredentials("user", "passwd") 
     ); 

     HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd"); 
     HttpResponse response = Client.execute(httpGet); 

     System.out.println("response = " + response); 

     BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     StringBuilder responseString = new StringBuilder(); 
     String line = ""; 
     while ((line = breader.readLine()) != null) { 
      responseString.append(line); 
     } 
     breader.close(); 
     String responseStr = responseString.toString(); 
     System.out.println("responseStr = " + responseStr); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

बेस 64.encodeBase64String ("उपयोगकर्ता: passwd" .getBytes()); मेरे लिए काम किया डेटाटाइप कनवर्टर.प्रिंटबेस 64 बाइनरी() ने भी मेरे लिए काम किया। यह हो सकता है कि आपने पहले के मामले में संदेश निकाय में गलती की और इससे बुरा अनुरोध हुआ। या शायद यह सर्वर पर निर्भर करता है। – rents

+0

हे भगवान! धन्यवाद, मेरे मामले के लिए भी काम कर रहा है:] – xxxvodnikxxx

12

यह बेस 64 एन्कोडिंग के संबंध में किए गए कुछ परिवर्तनों के साथ ऊपर दिए गए स्वीकृत उत्तर से कोड है। नीचे कोड संकलित करता है।

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import org.apache.commons.codec.binary.Base64; 


public class HttpBasicAuth { 

    public static void main(String[] args) { 

     try { 
      URL url = new URL ("http://ip:port/login"); 

      Base64 b = new Base64(); 
      String encoding = b.encodeAsString(new String("test1:test1").getBytes()); 

      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("POST"); 
      connection.setDoOutput(true); 
      connection.setRequestProperty ("Authorization", "Basic " + encoding); 
      InputStream content = (InputStream)connection.getInputStream(); 
      BufferedReader in = 
       new BufferedReader (new InputStreamReader (content)); 
      String line; 
      while ((line = in.readLine()) != null) { 
       System.out.println(line); 
      } 
     } 
     catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
1

, हैडर सरणी

 String auth = Base64.getEncoder().encodeToString(("test1:test1").getBytes()); 
     Header[] headers = { 
       new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()), 
       new BasicHeader("Authorization", "Basic " +auth) 
       }; 
संबंधित मुद्दे