Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JAVA中带有JSON字符串的HTTP POST请求_Java_Json_Http Post_Httpclient_Httpurlconnection - Fatal编程技术网

JAVA中带有JSON字符串的HTTP POST请求

JAVA中带有JSON字符串的HTTP POST请求,java,json,http-post,httpclient,httpurlconnection,Java,Json,Http Post,Httpclient,Httpurlconnection,我必须使用已经生成的JSON字符串发出http Post请求。 我尝试了两种不同的方法: 1.HttpURLConnection 2.HttpClient 但我从他们两个身上得到了同样的“不想要的”结果。 到目前为止,我使用HttpURLConnection的代码是: public static void SaveWorkflow() throws IOException { URL url = null; url = new URL(myURLgoeshere); H

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

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

    }
}
到目前为止,我与HttpClient的代码是:

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 ();
    }
}
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":[]}

有什么想法吗?

最后我设法找到了解决问题的办法

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();
        }
    }
public static void SaveWorkFlow()引发IOException
{
CloseableHttpClient httpClient=HttpClients.createDefault();
HttpPost=新的HttpPost(Myurlgoesher);
List params=new ArrayList();
添加(新的BasicNameValuePair(“任务”、“保存模型”);
添加(新的BasicNameValuePair(“代码”,generatedJSONString));
CloseableHttpResponse响应=null;
扫描仪输入=空;
尝试
{
post.setEntity(新的UrlEncodedFormEntity(params));
response=httpClient.execute(post);
//System.out.println(response.getStatusLine());
HttpEntity=response.getEntity();
in=新扫描仪(entity.getContent());
while(在.hasNext()中)
{
System.out.println(in.next());
}
EntityUtils.consume(实体);
}最后
{
in.close();
response.close();
}
}

实现这一点的另一种方法如下所示:

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

您是否尝试将字符串转换为对象(解析JSON)而不在中间使用HTTP传输步骤?尝试使用GetryJSONString。Times()看起来像使用REST Web服务;您可能希望通过应用JAX-RS API使您的生活变得非常简单。事实上,我首先将json作为一个对象生成,然后将其转换为字符串…您可以列出为此所需的JAR吗?现在开始-->编译组:“org.apache.httpcomponents”,名称:“httpclient android”,版本:“4.3.5.1”|但它已被弃用,因此请尝试寻找其他版本:-\