android - httpurlconnection 中的问题获取状态 500

标签 android httpurlconnection

我正在尝试通过 url 登录,我在 httpurlconnevtion 中收到状态码 500

public static String excutePost(String targetURL, String urlParameters)
  {
    URL url;
    HttpURLConnection connection = null;  
    try {
      //Create connection
      url = new URL(targetURL);
      connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", 
           "application/x-www-form-urlencoded");
      connection.setRequestProperty("Connection", "Keep-Alive");    
      connection.setRequestProperty("Content-Length", "" + 
               Integer.toString(urlParameters.getBytes().length));
      connection.setRequestProperty("Content-Language", "en-US");  
      connection.setRequestProperty("Accept-Encoding", ""); 
      connection.setUseCaches (false);
      connection.setDoInput(true);
      connection.setDoOutput(true);

      //Send request
      DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
      wr.writeBytes (urlParameters);
      wr.flush ();
      wr.close ();

      System.out.println("status :"+connection.getResponseCode());
      System.out.println("getErrorStream() :"+connection.getErrorStream());
      //Get Response    
      InputStream is = connection.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      StringBuffer response = new StringBuffer(); 
      while((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
      }
      rd.close();
      return response.toString();

    } catch (Exception e) {

      e.printStackTrace();
      return null;

    } finally {

      if(connection != null) {
        connection.disconnect(); 
      }
    }
  }

我的参数是

String urlParameters =
                        "pwd1=" + URLEncoder.encode("DEMO123", "UTF-8") +
                        "&badge=" + URLEncoder.encode("1233", "UTF-8");

我正在获取 logcat

status :500
getErrorStream() :libcore.net.http.FixedLengthInputStream@417bc5c0

谢谢

**EDITED 2**

我也试过

DataOutputStream dos = new DataOutputStream(connection.getOutputStream());

        // Add badge
        dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
        dos.writeBytes("Content-Disposition: form-data; name='badge';");
        dos.writeBytes(LINE_END + LINE_END);
        dos.writeBytes("1233");
        dos.writeBytes(LINE_END);

        // Add password
        dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
        dos.writeBytes("Content-Disposition: form-data; name='pwd1';");
        dos.writeBytes(LINE_END + LINE_END);
        dos.writeBytes("DEMO123");
        dos.writeBytes(LINE_END);

最佳答案

500 表示 Internal Server Error。您这边可能没有错误,它在服务器上。即使您发送错误并导致服务器返回 500,这仍然是服务器问题。

编辑: 好的,服务器应该返回类似 400 Bad Request 而不是 500 Internal Server Error 但我现在发现了你的错误:

connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));

...

//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (urlParameters);

这里的问题是您首先使用 getBytesurlParameters 获取字节,其中(引用 javadoc):

Encodes this String into a sequence of bytes using the platform's default charset

然后使用 DataOutputStream.writeBytes 写入字节(引用 javadoc):

Each character in the string is written out, in sequence, by discarding its high eight bits.

总之,您的Content-Length 与数据不匹配。所以服务器返回给你

java.io.IOException: exceeded content-length limit of 20 bytes

解决方案:

//consider urlParameters.getBytes("UTF-8") method instead of using default encoding
byte[] bodyData = urlParameters.getBytes(); 
connection.setRequestProperty("Content-Length", Integer.toString(bodyData.length));

...

//Send request
InputStream out = connection.getOutputStream();
out.write(bodyData);

编辑 2: Edit 1 肯定有效,但是,再次查看问题,我认为错误肯定是由服务器引起的。我认为服务器正在返回一个错误的 Content-Length header ,当在 Android 上读取数据时,系统意识到来自服务器的数据多于 Content 应有的数据-Length 并抛出异常,同时将状态代码替换为 500,因为它确实是服务器错误。

编辑 3:

connection.setRequestProperty("Content-Language", "en-US");  
connection.setRequestProperty("Accept-Encoding", ""); 

您应该将 Content-Encoding 设置为 UTF-8 而不是空的,而不是设置此处不需要的 Content-Language Accept-Encoding,您应该添加真正期望的 MIME 类型。我相信这是一个服务器错误,但如果您正确设置请求 header ,它可能不会出现。

关于android - httpurlconnection 中的问题获取状态 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15358996/

相关文章:

android - 为什么链元素之间的空间如此之大?

android - NDK 文件未与 Gradle Android 同步

java - HttpURLConnection 关闭 IO 流

java - 执行 PUT 请求时出现 HTTP 403

java - 在Java中,如何为FileChannel设置进度条?

android - 在 Recyclerview 中下载图片

android - 如何检测 Android ListView 上的双击/点击?

android - 所有具有特征的 Android 设备列表

java - HttpURLConnection 在 getResponseCode 处抛出 NullPointerException

java - 如何在 Java 中执行 HTTP GET?