2017-09-05 78 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(); 
        } 
       }}