2017-09-05 2 views
1
내가 HTTPS 요청을 수행 할

설정 유지, 나는이 일을 해요 :HttpsURLConnection에 잘못된 매개 변수

conn 객체를 디버깅하는 동안 내가이 일을 해요하지만
String myParams = "param1=ok&param2=ok"; 
byte[] outputInBytes = myParams.toString().getBytes("UTF-8"); 
URL url = new URL("https://myurl.com/sendData.asp"); 
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
conn.setDoOutput(true); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("Set-Cookie", sessionCookie); 
conn.setRequestProperty("Accept", "text/html"); 
conn.setRequestProperty("Content-Length", "" + Integer.toString(outputInBytes.length)); 
OutputStream os = conn.getOutputStream(); 
os.write(outputInBytes); 
os.close(); 

response = conn.getResponseCode(); 

InputStream in = null; 
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); 

in = conn.getInputStream(); 
int c; 
while ((c = in.read()) != -1) 
    byteArrayOut.write(c); 

byte[] byteArray = byteArrayOut.toByteArray(); 
s = new String(byteArray); 

는, 여기에 정보입니다 내가 얻을 :

enter image description here

나는 어떤 문제없이 응용 프로그램의 iOS 버전에서 동일한 엔드 포인트를 사용하고 있기 때문에 서버 측의 문제라고 생각하지 않습니다. 그러면이 문제가 발생할 수있는 이유는 무엇입니까?

+0

화면 캡처 출력을 샘플링 할 때 어떤 코드 줄이 디버거였습니까? Android에서 코드를 실행할 때 적어도 ASP에서 끝점에 도달했는지 확인 했습니까? –

+0

원시 Http 클라이언트를 사용하는 것은 매우 까다 롭습니다. 개장과 같은 라이브러리를 사용해보십시오. 내 인생을 더 쉽게 만들었습니다. –

+0

@TimBiegeleisen'conn.getOutputStream()'줄에서 실행을 중단했습니다. 나는 또한 URL이 실제로 내가 기대하는 것임을 확인했다. – Someday

답변

0

나는 일반적으로 핵심 자바 HTTP 라이브러리를 사용하지 않는 감사하지만 당신은 응답을 읽을 수있는 시도를 할 수없는 경우, 요청이 실제로 아무것도하지 않는 것 같다.

끝에 conn.getInputStream().read()을 추가하면 요청을 보내야합니다.

String myParams = "param1=ok&param2=ok"; 
    byte[] outputInBytes = myParams.toString().getBytes("UTF-8"); 
    String request = "https://requestb.in/1emd86r1"; 
    URL url = new URL(request); 
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
    conn.setDoOutput(true); 
    conn.setRequestMethod("POST"); 
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
    conn.setRequestProperty("Accept", "text/html"); 
    conn.setRequestProperty("Content-Length", "" + Integer.toString(outputInBytes.length)); 

    //this is needed for reqeustbin 
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); 

    OutputStream os = conn.getOutputStream(); 
    os.write(outputInBytes); 
    os.close(); 

    conn.getInputStream().read(); //without this the request was not send. with it it is send. 

그러나, 나는 당신의 요청을 위해 이것을 사용하지 않는 것이 좋습니다 :

이를 테스트하기 위해 나는 다음을 시도했다. 대신 아파치 HttpClient/OkHttp/Netty와 같은 라이브러리를 사용하려고 시도 할 수도 있습니다.

+0

답장을 보내 주셔서 감사합니다. 나는 사용되는 전체 코드 조각을 붙여 넣지는 않았지만 실제로 입력 스트림을 읽었고 관련성이 없다고 생각하면서 단순히 내 질문에 추가하지 않았습니다. 혼란을 피하기 위해 질문에 추가하겠습니다. – Someday

+0

또한이 libs, 조언을 주셔서 감사합니다 – Someday

+0

fyi 덕분에, 디버거가 httpurlconnection과 좋은 경기를하지 않는 것 같습니다. 위의 코드와 함께 successfuly 게시 요청을하지만 디버거가 여전히 메서드로 "얻을"보고합니다. –

0

Android 코드에서 사용하는 패턴은 코드 스 니펫에있는 패턴과 상당히 유사하지만 다음과 같은 추가로 끝납니다 코드 :

// at this point the call is actually made 
int responseCode = conn.getResponseCode(); 

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
String inputLine; 
StringBuffer response = new StringBuffer(); 

while ((inputLine = in.readLine()) != null) { 
    response.append(inputLine); 
} 
in.close(); 

// your response data is available in 'response' 

ASP 엔드 포인트의 응답을 읽고 사용할 계획 인 경우 유용 할 수 있습니다.

+0

답장을 보내 주셔서 감사합니다. 제가 p.streef에 말했듯이 실제로 제가하고있는 일이지만, 그것이 적절하다고 생각하지 않았기 때문에 언급하지 않았습니다. – Someday

+0

아직 내 질문에 답변하지 않았습니다. 서버 쪽 끝점에 도달 했습니까? 통화에서 어떤 데이터가 다시 나타 납니까? –

+0

예, 서버가 오류 응답 인 "0"을 반환하지만 여전히 응답입니다. 실제로 백엔드 부분에서는 작동하지 않으므로이 문제에 대한 자세한 내용은이 부분을 담당하는 개발자에게 문의 할 것입니다. – Someday

0

내 https 요청을 만드는 방법입니다. 내 방법을 시도해보고 효과가 있는지 확인할 수 있습니다.

public void makeRequest(){ 


try { 

        CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
        InputStream caInput; 


        //I have stored my C.A certificates in Resources.raw file, Get it this way 
        caInput = new BufferedInputStream(getResources().openRawResource(R.raw.godaddysecure)); 



        Certificate ca; 

        try { 
         ca = cf.generateCertificate(caInput); 
         System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); 
         Log.d("MyApp", "Certificate " + ((X509Certificate) ca).getSubjectDN()); 
        } finally { 
         caInput.close(); 
        } 


        // Create a KeyStore containing our trusted CAs 


        String keyStoreType = KeyStore.getDefaultType(); 
        KeyStore keyStore = KeyStore.getInstance(keyStoreType); 
        keyStore.load(null, null); 
        keyStore.setCertificateEntry("ca", ca); 


        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); 
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); 
        tmf.init(keyStore); 

        Log.d("MyApp", "KeyStore Initialized "); 


        // Create a TrustManager that trusts the CAs in our KeyStore 


        // Create an SSLContext that uses our TrustManager 


        SSLContext context = SSLContext.getInstance("TLS"); 
        context.init(null, tmf.getTrustManagers(), null); 
        Log.d("MyApp", "SSL context call "); 
        URL url = new URL("Your String URl here"); 


        urlConnection = 
          (HttpsURLConnection) url.openConnection(); 


        // Tell the URLConnection to use a SocketFactory from our SSLContext 

        //Replace below with your own request properties 
        urlConnection.setRequestProperty("Your Request properties here"); 
        urlConnection.setDoOutput(true); 
        urlConnection.setRequestMethod("POST"); 
        urlConnection.setUseCaches(false); 
        urlConnection.setRequestProperty("Accept", "text/xml"); 
        urlConnection.setSSLSocketFactory(context.getSocketFactory()); 


        try { 

         //Write your output stream to server here 
         String body = "Boody of request i was sending"; 

         OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); 
         wr.write(body); 

         wr.flush(); 

        } catch (Exception e) { 

         Log.d("MyApp", "Body write Exception " + e.toString()); 
        } 


        int responseCode = urlConnection.getResponseCode(); 


        InputStream in = urlConnection.getInputStream(); 


        //get your server response as below 
        reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
        String line = ""; 
        StringBuilder bd = new StringBuilder(); 

        System.out.println("Before String builder " + reader); 

        while ((line = reader.readLine()) != null) { 

         System.out.println("Before String builder while loop"); 
         String output = bd.append(line).toString(); 
         System.out.println("Output " + output + " code " + responseCode); 
         strResponse = output; 


        } 

       } catch (RuntimeException e) { 

        Log.d("Mfinance", "Login Activity Exception"); 
        // e.printStackTrace(); 
       } finally { 
        try { 

         reader.close(); 
        } catch (Exception e) { 

         Log.d("Mfinance", "Loans Activity Exception"); 
         // e.printStackTrace(); 
        } 
       }}