HttpsURLConnection继续设置错误的参数

时间:2017-09-05 13:11:27

标签: android

我想执行HTTPS请求,我这样做:

public Map<Object, Object> upload(ModelMap model) {
        Map<Object, Object> responseMap = new HashMap<>();
        sendMailBean = (SendMailBean) model.get("sendMailBean");

        FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
        formDataMultiPart.field("firstName", sendMailBean.getFirstname());
        formDataMultiPart.field("lastName", sendMailBean.getLastname());
        formDataMultiPart.field("fromAddress", sendMailBean.getEmail());
        formDataMultiPart.field("subject", sendMailBean.getSubject());
        formDataMultiPart.field("text", sendMailBean.getMessage());
        List<MultipartFile> files = sendMailBean.getAttachments();
        try {
            for(MultipartFile file : files) {
                File convFile = convert(file);
                FileDataBodyPart filePart = new FileDataBodyPart("files", convFile);
                filePart.setContentDisposition(FormDataContentDisposition.name("files").fileName(file.getOriginalFilename()).build());
                formDataMultiPart.bodyPart(filePart);
            }
            Client client = new Client();       
            WebResource webResource = client.resource(----rest url-----);
            ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, formDataMultiPart);


            if (response.getStatus() != 200) {
                model.addAttribute("errormsg", "Failed : HTTP error code : " + response.getStatus());
                responseMap.put("model", model);
                responseMap.put("redirectToPage", "redirect:/views/error");
            } else {
                //          responseMap.put("redirectToPage", "/views/email");

                responseMap.put("model", model);
                responseMap.put("redirectToPage", "");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return responseMap;
    }

    public File convert(MultipartFile file)
    {    
        File convFile = new File(file.getOriginalFilename());
        try {
            convFile.createNewFile(); 
            FileOutputStream fos = new FileOutputStream(convFile); 
            fos.write(file.getBytes());
            fos.close(); 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return convFile;
    }

虽然我这样做,但在调试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版本上使用相同的端点而没有任何问题。那么什么可能导致这个问题?

谢谢

3 个答案:

答案 0 :(得分: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这样的库

答案 1 :(得分: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端点的响应,这可能很有用。

答案 2 :(得分: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();
                    }
                }}