正しい出力を提供するこのコマンドを実行するためにこれがあり、HttpUrlConnection(または任意のサードパーティライブラリ)を使用してJavaでこれをエミュレートしたい
curl http://localhost/myservice/ -v -H 'Content-Type: multipart/form-data' -F 'file=@/home/xyz/abc.jpg' -F 'type=image' -F 'id=123'
このサービスは、ファイル、タイプ、およびIDを受け入れます。
私の現在のコードは次のようになります-
String urlToConnect = "http://localhost/myservice/";
String boundary = Long.toHexString( System.currentTimeMillis() ); // Just generate some unique random value
HttpURLConnection connection = (HttpURLConnection) new URL( urlToConnect ).openConnection();
connection.setDoOutput( true ); // This sets request method to POST.
connection.setRequestProperty( "Content-Type", "multipart/form-data; boundary="+boundary);
PrintWriter writer = null;
try
{
writer = new PrintWriter( new OutputStreamWriter( connection.getOutputStream(), "UTF-8" ) );
writer.println( "--" + boundary );
// -F type =1
writer.println( "Content-Disposition: form-data; name=\"type\"" );
writer.println( "Content-Type: text/plain; charset=UTF-8" );
writer.println();
writer.println( "image" );
//writer.println( "--" + boundary );
// -F id=1
writer.println( "Content-Disposition: form-data; name=\"id\"" );
writer.println( "Content-Type: text/plain; charset=UTF-8" );
writer.println();
writer.println( 123 );
//writer.println( "--" + boundary );
writer.println( "Content-Disposition: form-data; name=\"file\"; filename=\"abc.jpg\"" );
writer.println( "Content-Type: image/jpeg;" );
writer.println();
BufferedReader reader = null;
try
{
reader = new BufferedReader( new InputStreamReader( new FileInputStream(
"/home/xyz/abc.jpg" ), "UTF-8" ) );
for( String line; (line = reader.readLine()) != null; )
{
writer.println( line );
}
}
finally
{
if( reader != null ) try
{
reader.close();
}
catch( IOException logOrIgnore )
{
}
}
}
finally
{
if( writer != null ) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println( responseCode ); // Should be 200
StringBuffer responseContent = new StringBuffer();
BufferedReader rd = null;
try
{
rd = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
}
catch( Exception e )
{
rd = new BufferedReader( new InputStreamReader( connection.getErrorStream() ) );
}
String temp = null;
while( (temp = rd.readLine()) != null )
{
responseContent.append( temp );
}
System.out.println( "Response : " + responseContent );
}