简体   繁体   English

服务器返回的HTTP响应代码:400表示URL HttpURLConnection.getInputStream表示JSON POST数据字符串

[英]Server returned HTTP response code: 400 for URL HttpURLConnection.getInputStream for JSON POST data string

I'm trying to establish a HttpUrlConnection to a URL for its POST method and trying to POST JSON data in the request header. 我正在尝试为其URL的POST方法建立一个HttpUrlConnection,并尝试在请求标头中发布JSON数据。 In doing so i'm getting the response code 400 for the URL with the below payload: 这样做时,我得到具有以下负载的URL响应代码400:

    {
       "classResolver":"EXTERNAL_DATA",
       "id":12345,
       "idEntity":"MUM",
       "nameEntity":"XYZ",
       "olympicIdEntity":null,
       "sidCreator":"X123",
       "nameCreator":"XXX, Test",
       "createTime":"15-Jul-2015 17:56:36 GMT +05:30",
       "modifyTime":"15-Jul-2015 17:56:36 GMT +05:30",
       "valueDate":"15-Jul-2015",
       "submissionCutoff":"15-Jul-2015 17:56:36 GMT +05:30",
       "alertId":null,
       "repairFlagRequired":false,
       "callbackRequiredFlag":false,
       "statementRefDebit":null,
       "thirdPartyApproval":null,
       "thirdPartyApprDetails":null,
       "thirdPartyReln":null,
       "adviceRefDebit":null,
       "idTcc":null,
       "accName":null,
       "isAcctTPRest":false,
       "idEntityDebitAcc":null
    }

The total JSON payload has around 250 elements with almost the same data. JSON总有效载荷包含大约250个元素,几乎具有相同的数据。

The code is : 代码是:

    URLConnection connection = null;
    connection = url.openConnection();
    connection.setRequestProperty("reqHeaderInfoJson", objectMapper.writeValueAsString(jsonObj));
    connection.setRequestProperty("Accept", mediaType);
    connection.setRequestProperty("Content-Type", mediaType);
    BufferedReader br=null;
    StringBuilder sb=null;
    InputStreamReader isr=null;
    try {
        isr=new InputStreamReader(connection.getInputStream(), "UTF-8");
        br = new BufferedReader(isr);
        sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
    } catch (Exception e) {
        logger.error("Number of header copied => headerCount=" + e.getStackTrace(),e);
        e.printStackTrace();
    }

The same works with any other JSON string. 其他任何JSON字符串也一样。 There is a definite problem with the JSON string that i'm passing. 我传递的JSON字符串确实存在问题。 Can someone please suggest? 有人可以建议吗?

try adding the following to your code 尝试将以下内容添加到您的代码中

connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();

then replaced 然后更换

InputStreamReader isr = new InputStreamReader(...)

for 对于

InputStream input =new BufferInputStream(url.openStream());

if you just want to get JSON objects from server I leave the following code works for me without problems. 如果您只想从服务器获取JSON对象,那么下面的代码对我来说没有问题。 I work with JSON objects stored nodes 1500 我使用JSON对象存储节点1500

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(params,"UTF-8");
                encodedEntity.setContentEncoding(HTTP.UTF_8);
                httpPost.setEntity(encodedEntity);
                //httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        //codigo pruebna
        response = new Scanner(httpResponse.getEntity().getContent(),"UTF-8").useDelimiter("\\A").next();
        /*httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity,"utf-8");*/

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

} }

then you must use it as follows 那么您必须按以下方式使用它

// Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();
        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

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

相关问题 HttpUrlConnection.getInputStream 上的 HTTP 响应代码 401 - HTTP Response code 401 on HttpUrlConnection.getInputStream 服务器返回URL的HTTP响应代码:400:HttpURLConnection错误 - Server returned HTTP response code: 400 for URL : HttpURLConnection Error Android HttpURLConnection.getInputStream在HTTP POST中的奇怪行为 - Strange behaviour of Android HttpURLConnection.getInputStream in HTTP POST HttpURLConnection错误-java.io.IOException:服务器返回的HTTP响应代码:URL的400 - HttpURLConnection Error - java.io.IOException: Server returned HTTP response code: 400 for URL 服务器返回 HTTP 响应代码:400:模拟 HttpURLConnection 时 - Server returned HTTP response code: 400 : When mocking HttpURLConnection 服务器返回HTTP响应代码:400为URL: - Server returned HTTP response code: 400 for URL: HttpURLConnection.getInputStream()阻止 - HttpURLConnection.getInputStream() blocks 服务器返回 HTTP 响应代码:400 用于在 java httpurlconnection 中生成 oauth 令牌 - Server returned HTTP response code: 400 for oauth token generation in java httpurlconnection yql:服务器返回的HTTP响应代码:URL的400 - yql : Server returned HTTP response code: 400 for URL Bootstrapexception:服务器返回的Sonar URL HTTP响应代码:400 - Bootstrapexception : Server returned HTTP response code: 400 for Sonar URL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM