2012-12-27 11 views
6

をHTTPS POSTリクエストを送信します。 リクエストを送信しようとすると、SSLサーバー証明書の例外が発生します。 この問題を解決するにはどうすればよいですか?は、これは私のHTTP JSON私はHTTPS POSTリクエストを使用してサーバーに投稿する必要があり</p> <pre><code>{ "User": { "Name": "Compulsary","Password": "Compulsary" } } </code></pre> <p>あるサーバに

私は何を試しましたか?

HTTPPostHTTPClientと試してみました。 SSL例外。 私はURLConnectionを使ってみましたが、SSL証明書のチェックを無視しました。 401と405の応答コードを取得しています。

問題文:

は、(リクエストが安全であるHTTPSを受け入れる)サーバーに上記のPOSTリクエストを送信します。 これをAndroidでどのように達成するには?

私はこのコードを試しましたが、私は405エラーを受け取りますか?

// always verify the host - dont check for certificate 
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 
    public boolean verify(String hostname, SSLSession session) { 
     return true; 
    } 
}; 

/** 
* Trust every server - dont check for any certificate 
*/ 
private static void trustAllHosts() { 
    // Create a trust manager that does not validate certificate chains 
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { 
     public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
      return new java.security.cert.X509Certificate[] {}; 
     } 

     public void checkClientTrusted(X509Certificate[] chain, 
       String authType) throws CertificateException { 
     } 

     public void checkServerTrusted(X509Certificate[] chain, 
       String authType) throws CertificateException { 
     } 
    } }; 

    // Install the all-trusting trust manager 
    try { 
     SSLContext sc = SSLContext.getInstance("TLS"); 
     sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
     HttpsURLConnection 
       .setDefaultSSLSocketFactory(sc.getSocketFactory()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

private void makeRequest() { 
    URL url = null; 
    HttpsURLConnection urlConnection = null; 
    try { 
     url = new URL("https://wbapi.cloudapp.net:443/api/User/LocalLogin"); 
    } catch (MalformedURLException e2) { 
     // TODO Auto-generated catch block 
     e2.printStackTrace(); 
    } 
    StringBuilder sb = new StringBuilder(); 

    try { 
     trustAllHosts(); 
     urlConnection = (HttpsURLConnection) url.openConnection(); 
     urlConnection.setHostnameVerifier(DO_NOT_VERIFY); 
     urlConnection.setDoOutput(true); 
     urlConnection 
       .setRequestProperty("Content-Type", "application/json"); 
     urlConnection.setFixedLengthStreamingMode(urlConnection 
       .getContentLength()); 
    } catch (IOException e2) { 
     // TODO Auto-generated catch block 
     e2.printStackTrace(); 
    } 

    try { 
     urlConnection.connect(); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    JSONObject jsonParam = new JSONObject(); 
    try { 
     jsonParam.put("Name", "dog"); 
     jsonParam.put("Password", "123"); 
     Log.v("Length", "" + urlConnection.getContentLength()); 
     int HttpResult = urlConnection.getResponseCode(); 
     Toast.makeText(LoginActivity.this, "Response" + HttpResult, 
       Toast.LENGTH_LONG).show(); 
     if (HttpResult == HttpsURLConnection.HTTP_OK) { 
      System.out.println("ok"); 
      Log.v("Hi", "" + "Trex"); 
      BufferedReader br = new BufferedReader(new InputStreamReader(
        urlConnection.getInputStream(), "utf-8")); 
      String line = null; 
      while ((line = br.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      br.close(); 

      System.out.println("" + sb.toString()); 
      Toast.makeText(LoginActivity.this, "" + sb.toString(), 
        Toast.LENGTH_LONG).show(); 

     } else { 
      System.out.println("Here" + urlConnection.getResponseMessage()); 
     } 
    } catch (MalformedURLException e) { 

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

     e.printStackTrace(); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

Logcatエントリー

12-27 13:41:27.228: V/Length(3034): 72 
12-27 13:41:27.248: I/System.out(3034): HereMethod Not Allowed 
+0

こちらをご覧ください:http://stackoverflow.com/questions/4461360/how-to-install-trusted-ca-certificate-on-android-deviceこれはすべての場合に機能しません。 – neworld

+1

私はたくさんのstackoverflowの質問を見て、役に立たなかった –

+0

誰もあなたの問題についての詳細を説明し、あなたのコードを表示する必要がありますあなたが本当に助けなければ、試しが必要 – neworld

答えて

10

ステップ1:クラスMySSLSocketFactoryを作成し、コードの下を含む:

public class MySSLSocketFactory extends SSLSocketFactory { 
    SSLContext sslContext = SSLContext.getInstance("TLS"); 

    public MySSLSocketFactory(KeyStore truststore) 
        throws NoSuchAlgorithmException, KeyManagementException, 
        KeyStoreException, UnrecoverableKeyException { 
      super(truststore); 

      TrustManager tm = new X509TrustManager() { 
        public void checkClientTrusted(X509Certificate[] chain, 
            String authType) throws CertificateException { 
        } 

        public void checkServerTrusted(X509Certificate[] chain, 
            String authType) throws CertificateException { 
        } 

        public X509Certificate[] getAcceptedIssuers() { 
          return null; 
        } 
      }; 

      sslContext.init(null, new TrustManager[] { tm }, null); 
    } 

    @Override 
    public Socket createSocket(Socket socket, String host, int port, 
        boolean autoClose) throws IOException, UnknownHostException { 
      return sslContext.getSocketFactory().createSocket(socket, host, port, 
          autoClose); 
    } 

    @Override 
    public Socket createSocket() throws IOException { 
      return sslContext.getSocketFactory().createSocket(); 
    } 

} 

ステップ2:ステップ3

public class WebClientDevWrapper { 

    public static HttpClient getNewHttpClient() { 
     try { 
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
      trustStore.load(null, null); 

      SSLSocketFactory sf = new MySSLSocketFactory(trustStore); 
      sf.setHostnameVerifier(
        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

      HttpParams params = new BasicHttpParams(); 
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

      SchemeRegistry registry = new SchemeRegistry(); 
      registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
      registry.register(new Scheme("https", sf, 443)); 

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

      return new DefaultHttpClient(ccm, params); 
     } catch (Exception e) { 
      return new DefaultHttpClient(); 
     } 
    } 

} 

をクラスWebClientDevWrapperを作成し、以下のコードを含みます:アクティビティ内または他の場所にメソッドを作成します。このメソッドは、Web呼び出しを行うために使用されます。

/** 
    * Request JSON based web service to get response 
    * 
    * @param url 
    *   - base URL 
    * @param request 
    *   - JSON request 
    * @return response 
    * @throws ClientProtocolException 
    * @throws IOException 
    * @throws IllegalStateException 
    * @throws JSONException 
    */ 
    public HttpResponse request(String url, JSONObject request) 
      throws ClientProtocolException, IOException, IllegalStateException, 
      JSONException { 

     DefaultHttpClient client = (DefaultHttpClient) WebClientDevWrapper.getNewHttpClient(); 

      HttpPost post = new HttpPost(url); 
      post.setEntity(new StringEntity(request.toString(), "utf-8")); 
      HttpResponse response = client.execute(post); 
      return response; 
     } 
    } 

ステップ4:メソッドを呼び出し、応答を取得します。

+0

MySSLSocketFactoryとは何ですか? –

+0

@RajeevNB oops私はステップ-1として含まれていることを忘れてしまった。チェック –

+0

JSONObjectオブジェクト=新しいJSONObject(); \t \t try { \t \t \t object.put( "Name"、 "dog"); \t \t \t object.put( "Password"、 "123"); \t \t}キャッチ(JSONException電子){ \t \t \t // TODO自動生成されたcatchブロック \t \t \t e.printStackTrace(); \t \t}私は上記のJSON用のオブジェクトですか?それが正しいか ? –

0

私は、HTTPS/HTTP/wift/3Gの組み合わせのために以下のコードを使用して、それが

public class CustomHttpClient { 
private static DefaultHttpClient customHttpClient; 

/** A private Constructor prevents instantiation */ 
private CustomHttpClient() { 
} 

public static synchronized DefaultHttpClient getHttpClient() { 
    if (customHttpClient == null) { 
     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, 
       HTTP.DEFAULT_CONTENT_CHARSET); 
     HttpProtocolParams.setUseExpectContinue(params, true); 
     HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"); 
     ConnManagerParams.setTimeout(params, 1000); 
     HttpConnectionParams.setConnectionTimeout(params, 5000); 
     HttpConnectionParams.setSoTimeout(params, 10000); 
     SchemeRegistry schReg = new SchemeRegistry(); 
     schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
     schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); 
     ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg); 
     customHttpClient = new DefaultHttpClient(conMgr, params); 
    } 
    return customHttpClient; 
} 

public Object clone() throws CloneNotSupportedException { 
    throw new CloneNotSupportedException(); 
} 

}

を役に立てば幸いとしていますサンプル

public static String Call(String URL, List<NameValuePair> postParameters) 
{ 
    BufferedReader in = null; 
    DefaultHttpClient httpClient; 
    StringBuffer sb = new StringBuffer(); 
    try{ 
     httpClient = CustomHttpClient.getHttpClient(); 

     HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false); //making 3G network works* 
     HttpPost request = new HttpPost(URL); 
     UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); 
     request.setEntity(formEntity); 
     HttpResponse response = httpClient.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
     sb.append(line + NL); 
     } 
     in.close(); 

    }catch(Exception ex) 
    { 
     ex.printStackTrace(); 

    } 
    return sb.toString(); 
} 
関連する問題

 関連する問題