Android HttpURLConnection写帖子数据

时间:2016-07-25 19:56:37

标签: java android httpurlconnection

我正在尝试通过HttpURLConnection发送帖子数据,但它似乎没有发送帖子数据。

我可以在尝试发送POST请求之前立即通过Toast输出数据,但是当我检查服务器端时,它会连接到PHP文件,但POST数据为空。

所以,我知道jsonObject中存在数据。     我也知道它使它成为try catch语句,但当我连接它时没有被正确发送或接收。

try {
        URL url = new URL(emailURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoOutput(true);

        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Content-Type", "application/json");
        conn.setRequestProperty( "charset", "utf-8");
        conn.setRequestProperty( "Content-Length", Integer.toString( jsonObject.toString().length() ));
        conn.setUseCaches( false );

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

        wr.write(jsonObject.toString());

          wr.close();

        BufferedReader reader = null;
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
        }

        String text = "";
        text = sb.toString();



    } catch (Exception e) {

        throw new RuntimeException(e);
    }

3 个答案:

答案 0 :(得分:0)

尝试添加方法以确保它真正连接到您的服务器。

修改您的代码,如:

    int responseCodeFromServer = -1;
    try {
         responseCodeFromServer=conn.getResponseCode();
    } catch (Exception e){
         e.printStackTrace();
    }

    if (responseCodeFromServer == HttpsURLConnection.HTTP_OK){
         BufferedReader reader = null;
         reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         StringBuilder sb = new StringBuilder();
        String line = null;

       // Read Server Response
       while ((line = reader.readLine()) != null) {
          // Append server response in string
          sb.append(line + "\n");
       }

       String text = "";
       text = sb.toString();
    }

因此,如果连接到服务器时出现问题,您将看到异常。

答案 1 :(得分:0)

在获得响应代码或输入或错误流之前,没有任何反应。你必须做其中一件事。

注意您不需要设置内容长度。 Java为您做到了这一点。同样,setDoOutput(true)将请求方法设置为POST。

答案 2 :(得分:-1)

conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString(jsonObject.toString().length() ));
conn.setUseCaches( false );

conn.connect(); // this is missing in your code

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());