2016-04-22 9 views
1

によってブロックされます:私はSYSOUTからログメッセージをコピーする場合のJava - curlコマンドを実行するためのランタイムを使用すると、私は私が実行しているWebサービスを消費curlコマンドを実行しようとしているプロキシ

String curl = "curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{\"field1\": \"value1\", \"field2\": \"value2\"}' 'http://localhost:8080/service'"; 
System.out.println(curl); 
try { 
    Runtime runtime = Runtime.getRuntime(); 
    Process process = runtime.exec(curl); 
    process.waitFor(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

をし、それを私の端末に貼り付けると、期待通りに動作しますが、javaコードを実行すると、サービスを見つけられないプロキシからhtmlページが返されるようです。

javaから実行するために別のものを追加する必要がありますか?

+0

が重複する可能性のProcessBuilderを活用した新たなコード(http://stackoverflow.com/questions/2586975/how-to [JavaでのcURLを使用する方法?] -use-curl-in-java) – pczeus

答えて

1

問題は、出力を読み取らないことです。あなたのコードを変更しましたので、となります。何らかの理由で正しくテストできないので、私は100%確信していません。

EDIT - これはうまくいきませんでした。これはあなたのために働くはずです。

String curl = "curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{\"field1\": \"value1\", \"field2\": \"value2\"}' 'http://localhost:8080/service'"; 
System.out.println(curl); 
try { 
    Runtime runtime = Runtime.getRuntime(); 
    Process process = runtime.exec(curl); 
    process.waitFor(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); //BufferedReader to read the output 
    StringBuilder sb = new StringBuilder(); //What will hold the entire console output 
    String line = ""; //What will hold the text for a line of the output 
    while ((line = reader.readLine()) != null) { //While there is still text to be read, read it 
     sb.append(line + "\n"); //Append the line to the StringBuilder 
    } 
    System.out.println(sb); //Print out the full output 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

EDIT - 代わりのRuntime

String curl = "curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{\"field1\": \"value1\", \"field2\": \"value2\"}' 'http://localhost:8080/service'"; 
ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", curl); 
builder.redirectErrorStream(true); 
Process p = builder.start(); 
StringBuilder sb = new StringBuilder(); 
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); 
String line; 
int linenum = 0; 
while (true) { 
    linenum++; 
    line = r.readLine(); 
    if (line == null) { 
     break; 
    } 
    sb.append(line); 
} 
System.out.println(sb); 
+0

最後にあなたのおかげで、カールからのフィードバックを得ることができました。プロキシのために失敗しているようですが、端末でコマンドを実行すると動作します私はまだ間違っていることを完全に理解していません。 –

+0

Javaプログラムにはさらに多くの権限が必要なのでしょうか?それが問題かもしれません。 'sudo'で実行してみてください。 – Dankrushen

+0

ええと、私は以前のものがうまくいかないと思っています。 'curl ="/bin/bash -c curl -Xを使用してみてください。-X POST - ヘッダー 'Content-Type:application/json' --header 'Accept:application/json' -d '{\ "field1 \": "value1 \"、\ "field2 \":\ "value2 \"} '' http:// localhost:8080/service '";'それはターミナル – Dankrushen

関連する問題