HTTPURLConnection给出响应码:500,但是在android中的restclient或postman上工作

时间:2016-09-10 10:16:49

标签: android httpurlconnection

我收到了HTTPURLConnection responsecode as 500。但是,当我使用Postman/RestClientContent-Type as application/json中传递相同的参数时,它会起作用并给我回复。 以下是我的doPost方法。

private String doPost(String jsonParam, String serviceUrl/*, String authorizeToken*/) {
        Log.e("doPost", "doPost called : URL : " + serviceUrl + "| jsonParam : " + jsonParam+"");
        HttpURLConnection urlConn;
        DataOutputStream printout;
        DataInputStream input;
        URL obj = null;
        String tempResponse = "";
        boolean error = false;
        try {
            obj = new URL(serviceUrl);
            urlConn = (HttpURLConnection) obj.openConnection();
            urlConn.setRequestMethod(POST);
            urlConn.setConnectTimeout(Constants.Connection.CONNECTION_TIMEOUT);
            urlConn.setReadTimeout(Constants.Connection.CONNECTION_TIMEOUT);
            urlConn.setRequestProperty("Content-Type", "application/json");
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);

            // Send POST output.
            printout = new DataOutputStream(urlConn.getOutputStream());
            printout.write(jsonParam.toString().getBytes());
            printout.flush();
            printout.close();
            int responseCode = urlConn.getResponseCode();
            Log.e("doPost", "HTTP URL Connection responseCode :" + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                tempResponse = readStream(urlConn.getInputStream());
            }
        } catch (MalformedURLException e) {
            error = true;
            e.printStackTrace();
        } catch (IOException e) {
            error = true;
            e.printStackTrace();
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
        } finally {
            if (error) {
                tempResponse = "";
            }
        }
        return tempResponse;
    }

任何人都可以帮我找到错误或解决问题吗?因为我没有得到同样的。

提前致谢。

1 个答案:

答案 0 :(得分:0)

尝试使用

更改您的用户代理
httpUrlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; Android 4.4.4; L39h;    Build/14.4.A.0.108; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.92 Mobile Safari/537.36 SogouMSE,SogouMobileBrowser/5.4.0");

这是一个Android浏览器用户代理。它适用于我http://translate.google.com

如果您未设置user-agent,将使用默认值。就我而言,它是

Dalvik/1.6.0 (Linux; U; Android 4.4.4; L39h Build/14.4.A.0.108)

它可能会被某些网站拒绝。