2017-09-05 32 views
1

我想執行一個HTTPS請求,我這樣做:HttpsURLConnection的不斷設置參數錯誤

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); 

雖然我這樣做,在調試conn對象,這裏是信息獲取:

enter image description here

我不認爲這是一個服務器端的問題,因爲我使用的應用的iOS版本相同的端點,而無需任何問題。那麼可能會導致這個問題呢?

謝謝

+0

當您採樣屏幕捕獲輸出時,哪行代碼是調試器?當你從Android運行你的代碼時,你是否證實你至少在ASP中達到了端點? –

+0

使用原始Http客戶端非常棘手,請嘗試使用庫改造。讓我的生活更輕鬆。 –

+0

@TimBiegeleisen我在'conn.getOutputStream()'行停止了執行。我也確保URL實際上是我期望的URL。 – Someday

回答

0

我通常不使用核心的Java 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. 

不過,我不建議使用這個,讓你的請求。相反,您可能想嘗試使用像Apache HttpClient/OkHttp/Netty的庫。

+0

感謝您的回覆。我沒有粘貼正在使用的整個代碼塊,但我實際上也在閱讀輸入流,根本沒有將它添加到我的問題中,因爲我認爲它不相關。我會將其添加到我的問題中以避免混淆。 – Someday

+0

也檢查這些庫,感謝您的建議 – Someday

+0

fyi,調試器似乎沒有與httpurlconnection很好玩。我成功地使用上面的代碼做了一個post請求,但調試器仍然報告「get」作爲方法 –

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(); 
        } 
       }}