简体   繁体   English

REST服务的POST函数返回空响应

[英]POST function for REST service returns empty response

I'm trying to do a post method for a REST service, but I'm not getting any response from server: 我正在尝试为REST服务执行post方法,但是我没有从服务器得到任何响应:

public JSONObject postValues (String strUrl, String strJsonArray) throws Exception{
    JSONObject jsonObject = null;
    URL url = new URL(strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    strJsonArray = "data=" + strJsonArray;

    Log.e("result",""+strJsonArray);

    OutputStream os = conn.getOutputStream();
    os.write(strJsonArray.getBytes());
    os.flush();

    conn.connect();

    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    StringBuilder sb = new StringBuilder();

    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        Log.e("output",output);
        sb.append(output);

    }

    Log.e("output",sb.toString());
    jsonObject = new JSONObject(sb.toString());

    conn.disconnect();

    return jsonObject;

}

When I see my logCat a get: 当我看到我的logCat物品时:

output {}

I know that the server is working right because I'm using the "advanced REST client" plugin of google chrome. 我知道服务器运行正常,因为我使用的是Google chrome的“高级REST客户端”插件。 If I call the URL manually (using the plugin of course)I get the desired answer: 如果我手动调用URL(当然使用插件),则会得到所需的答案:

{"message":"OK","code":200}

But if I try to use my function, my strJsonArray is inserted but I get an empty respond from server. 但是,如果我尝试使用我的函数,则会插入strJsonArray,但会收到服务器的空响应。

Is there anything wrong with my code?. 我的代码有什么问题吗?

Everything looks good... 一切看起来都很好...

You could use Wireshark to capture the packets sent to and received from the server using an emulator and the chrome rest client. 您可以使用Wireshark使用模拟器和chrome rest客户端捕获发送到服务器和从服务器接收的数据包。 Then you can compare them and maybe find out what's wrong. 然后,您可以比较它们,也许找出问题所在。

You could also check if theres something in the error stream ( conn.getErrorStream() ). 您还可以检查错误流中是否存在某些内容( conn.getErrorStream() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM