2013-12-23 14 views
9

すでに生成したJSON文字列を使用してhttp投稿リクエストを作成する必要があります。 私は別の2種類の方法を試みた:JSONを使用したHTTP POST要求(Javaの場合)

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

どうぞよろしくお願いします。

+0

あなただけのオブジェクトに文字列を変換しようとしたことがあり途中でHTTPの送信ステップを使わずに(JSONを解析する) –

+0

generatedJSONString.trim()を使用してみてください。 – aquaraga

+0

は、RESTfulなWebサービスを使用するようです。 JAX-RS APIを適用することで、あなたの人生を非常に簡単にすることができます。 – Gimby

答えて

8

は最後に、私は私の問題への解決策を見つけるために管理し、以下のように...これを達成する

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

この –

+1

の必須jarファイルをリストアップできますか?>コンパイルグループ: 'org.apache.httpcomponents'、name : 'httpclient-android'、バージョン: '4.3.5.1' |しかしそれは非難されているので、他のものを見つけようとする: - \ – XcodeNOOB

0

もう一つの方法は次のとおりです。

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(); 
    } 
} 
関連する問題