web-dev-qa-db-ja.com

HTTP POST JAVAにJSON文字列を含むリクエスト

既に生成したJSON文字列を使用してhttp Postリクエストを作成する必要があります。私は2つの異なる方法を試しました:

1.HttpURLConnection
2.HttpClient

しかし、私はそれらの両方から同じ「望ましくない」結果を取得します。これまでのHttpURLConnectionのコードは次のとおりです。

public static void SaveWorkflow() throws IOException {
    URL url = null;
    url = new URL(myURLgoeshere);
    HttpURLConnection urlConn = null;
    urlConn = (HttpURLConnection) url.openConnection();
    urlConn.setDoInput (true);
    urlConn.setDoOutput (true);
    urlConn.setRequestMethod("POST");
    urlConn.setRequestProperty("Content-Type", "application/json");
    urlConn.connect();

    DataOutputStream output = null;
    DataInputStream input = null;
    output = new DataOutputStream(urlConn.getOutputStream());

                /*Construct the POST data.*/
    String content = generatedJSONString;

    /* Send the request data.*/
    output.writeBytes(content);
    output.flush();
    output.close();

    /* Get response data.*/
    String response = null;
    input = new DataInputStream (urlConn.getInputStream());
    while (null != ((response = input.readLine()))) {
        System.out.println(response);
        input.close ();
    }
}

HttpClientを使用したこれまでの私のコードは次のとおりです。

public static void SaveWorkflow() {
    try {

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(myUrlgoeshere);
        StringEntity input = new StringEntity(generatedJSONString);
        input.setContentType("application/json;charset=UTF-8");
        postRequest.setEntity(input);
        input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
        postRequest.setHeader("Accept", "application/json");
        postRequest.setEntity(input); 

        HttpResponse response = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));

        String output;

        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
}

生成されたJsonStringは次のようになります。

{"description":"prova_Process","modelgroup":"","modified":"false"}

私が受け取る応答は次のとおりです。

{"response":false,"message":"Error in saving the model. A JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}

何か考えてください?

9
Blerta Dhimitri

最後に、私の問題の解決策を見つけることができました...

public static void SaveWorkFlow() throws IOException
    {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(myURLgoesHERE);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("task", "savemodel"));
        params.add(new BasicNameValuePair("code", generatedJSONString));
        CloseableHttpResponse response = null;
        Scanner in = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(params));
            response = httpClient.execute(post);
            // System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            in = new Scanner(entity.getContent());
            while (in.hasNext())
            {
                System.out.println(in.next());

            }
            EntityUtils.consume(entity);
        } finally
        {
            in.close();
            response.close();
        }
    }
8
Blerta Dhimitri

これを実現する別の方法は、次のとおりです。

public static void makePostJsonRequest(String jsonString)
{
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost postRequest = new HttpPost("Ur_URL");
        postRequest.setHeader("Content-type", "application/json");
        StringEntity entity = new StringEntity(jsonString);

        postRequest.setEntity(entity);

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(postRequest);
        long elapsedTime = System.currentTimeMillis() - startTime;
        //System.out.println("Time taken : "+elapsedTime+"ms");

        InputStream is = response.getEntity().getContent();
        Reader reader = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder builder = new StringBuilder();
        while (true) {
            try {
                String line = bufferedReader.readLine();
                if (line != null) {
                    builder.append(line);
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //System.out.println(builder.toString());
        //System.out.println("****************");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
0
sarjit07