JAVA中带有JSON字符串的HTTP POST请求 [英] HTTP POST request with JSON String in JAVA

查看:953
本文介绍了JAVA中带有JSON字符串的HTTP POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用我已生成的JSON字符串发出http Post请求。
我尝试了两种不同的方法:

I have to make a http Post request using a JSON string I already have generated. I tried different two different methods :

1.HttpURLConnection
2.HttpClient

但我得到了两个相同的不需要的结果。
到目前为止我的代码 HttpURLConnection 是:

but I get the same "unwanted" result from both of them. My code so far with HttpURLConnection is:

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 是:

My code so far with HttpClient is:

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如下所示:

Where generated JsonString is like this:

{"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":[]}

请知道吗?

推荐答案

最后我设法找到问题的解决方案...

Finally I managed to find the solution to my problem ...

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();
        }
    }

这篇关于JAVA中带有JSON字符串的HTTP POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆