2017-02-09 52 views
3

JSONデータ(文字列として渡す)をサーバーに送信するコードです(このコードは、私が調べたところでdataJSONの値として英語の文字を送信する場合に機能します):JSONデータをJavaのPOST経由で送信する

private static String sendPost(String url, String dataJSON) throws Exception { 

    System.out.println("Data to send: " + dataJSON); 


    URL obj = new URL(url); 
    HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
    String type = "application/json;charset=utf-8"; 

    // add reuqest header 
    con.setRequestMethod("POST"); 
    con.setRequestProperty("User-Agent", "Mozilla/5.0"); 
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
    con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length)); 
    con.setRequestProperty("Content-Type", type); 

    // Send post request 
    con.setDoOutput(true); 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    wr.writeUTF(dataJSON); 
    wr.flush(); 
    wr.close(); 

    int responseCode = con.getResponseCode(); 
    System.out.println("\nSending 'POST' request to URL : " + url); 
    System.out.println("Response Code : " + responseCode); 

    BufferedReader in = new BufferedReader(
      new InputStreamReader(con.getInputStream())); 
    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
     response.append(inputLine); 
    } 
    in.close(); 

    System.out.print("Response string from POST: " + response.toString() + "\n"); 
    return response.toString(); 

} 

問題点私は、例えばDHC Restlet Clientを使用して得られる正しい応答を得られません。

問題は私がdataJSONをUTF8でエンコードする必要があると思います。それはサーバーがそれを最も期待する方法です。 しかし、私はそれを変換して送信しようとする方法でコードにいくつかの問題があるようです。 上記の例でUTF8文字列として本文にデータを送信するのに役立つ人はいますか?

答えて

2

私は、このアプローチで解決だと思う:

private static String sendPost2(String urlStr, String dataJSON) throws Exception { 


    URL url = new URL(urlStr); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setConnectTimeout(5000); 
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
    conn.setDoOutput(true); 
    conn.setDoInput(true); 
    conn.setRequestMethod("POST"); 

    OutputStream os = conn.getOutputStream(); 
    os.write(dataJSON.getBytes("UTF-8")); 
    os.close(); 

    // read the response 
    InputStream in = new BufferedInputStream(conn.getInputStream()); 
    String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n")); 

    in.close(); 
    conn.disconnect(); 

    return result; 

} 

あなたはそれで問題を見た場合の代替を提案してください。

関連する問題