2016-09-15 15 views
1

簡単なサービステストのためにhttpクライアントを作成しようとしています。サーバー側では、以下のようにパース要求によってパラメータが読み込まれます。私は、フィールドは、それらのパラメータhttpclientでコントローラにパラメータを送信できません

final FileItemFactory factory = new DiskFileItemFactory(); 
final ServletFileUpload upload = new ServletFileUpload(factory); 
List<FileItem> fields = upload.parseRequest(request); 

を有するように、いくつかのパラメータを設定したいしかし、私はフィールドの値は常に空になるようにパラメータをHTTPクライアントからのものを設定することはできませんよ。私は次のコードを試しています

try { 
     CloseableHttpClient httpClient = HttpClients.createDefault(); 

     HttpPost httpPost = new HttpPost(url); 
     httpPost.setHeader("Accept", 
       "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); 
     httpPost.setHeader("Connection", "keep-alive"); 
     httpPost.setHeader("Content-Type", 
       "multipart/form-data; boundary=----WebKitFormBoundaryv1eAhALrGwBQXRIp"); 
     httpPost.setHeader("Host", "localhost:8080"); 
     httpPost.setHeader(
       "User-Agent", 
       "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36"); 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     nameValuePairs.add(new BasicNameValuePair("test", "red")); 
     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     CloseableHttpResponse response = httpClient.execute(httpPost); 
    } catch (Exception e) { 

    } 

私は何か間違っていることをお勧めします。

答えて

1

ここでは、addFormField()メソッドがあなたのトリックを行います。 addFormField()を使用すると、パラメータセットがフィールド変数に渡されます。

 public class MultipartUtility { 
     private final String boundary; 
     private static final String LINE_FEED = "\r\n"; 
     private HttpURLConnection httpConn; 
     private String charset; 
     private OutputStream outputStream; 
     private PrintWriter writer; 
     public MultipartUtility(String requestURL, String charset) 
      throws IOException { 
     this.charset = charset; 

     // creates a unique boundary based on time stamp 
     boundary = "===" + System.currentTimeMillis() + "==="; 

     URL url = new URL(requestURL); 
     httpConn = (HttpURLConnection) url.openConnection(); 
     httpConn.setUseCaches(false); 
     httpConn.setDoOutput(true); // indicates POST method 
     httpConn.setDoInput(true); 
     httpConn.setRequestProperty("Content-Type", 
       "multipart/form-data; boundary=" + boundary); 
     httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); 
     httpConn.setRequestProperty("Test", "Bonjour"); 
     outputStream = httpConn.getOutputStream(); 
     writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), 
       true); 
    } 

    public void addFormField(String name, String value) { 
     writer.append("--" + boundary).append(LINE_FEED); 
     writer.append("Content-Disposition: form-data; name=\"" + name + "\"") 
       .append(LINE_FEED); 
     writer.append("Content-Type: text/plain; charset=" + charset).append(
       LINE_FEED); 
     writer.append(LINE_FEED); 
     writer.append(value).append(LINE_FEED); 
     writer.flush(); 
    } 


    public void addFilePart(String fieldName, File uploadFile) 
      throws IOException { 
     String fileName = uploadFile.getName(); 
     writer.append("--" + boundary).append(LINE_FEED); 
     writer.append(
       "Content-Disposition: form-data; name=\"" + fieldName 
         + "\"; filename=\"" + fileName + "\"") 
       .append(LINE_FEED); 
     writer.append(
       "Content-Type: " 
         + URLConnection.guessContentTypeFromName(fileName)) 
       .append(LINE_FEED); 
     writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); 
     writer.append(LINE_FEED); 
     writer.flush(); 

     FileInputStream inputStream = new FileInputStream(uploadFile); 
     byte[] buffer = new byte[4096]; 
     int bytesRead = -1; 
     while ((bytesRead = inputStream.read(buffer)) != -1) { 
      outputStream.write(buffer, 0, bytesRead); 
     } 
     outputStream.flush(); 
     inputStream.close(); 

     writer.append(LINE_FEED); 
     writer.flush(); 
    } 

    public void addHeaderField(String name, String value) { 
     writer.append(name + ": " + value).append(LINE_FEED); 
     writer.flush(); 
    } 

    public List<String> finish() throws IOException { 
     List<String> response = new ArrayList<String>(); 

     writer.append(LINE_FEED).flush(); 
     writer.append("--" + boundary + "--").append(LINE_FEED); 
     writer.close(); 

     // checks server's status code first 
     int status = httpConn.getResponseCode(); 
     if (status == HttpURLConnection.HTTP_OK) { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        httpConn.getInputStream())); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       response.add(line); 
      } 
      reader.close(); 
      httpConn.disconnect(); 
     } else { 
      throw new IOException("Server returned non-OK status: " + status); 
     } 
     return response; 
    } 

    public static void main(String[] args) { 
      String charset = "UTF-8"; 
      File uploadFile1 = new File(filename); 
      String requestURL = url; 

      try { 
       MultipartUtility multipart = new MultipartUtility(requestURL, charset); 

       multipart.addHeaderField("User-Agent", "CodeJava"); 
       multipart.addHeaderField("Test-Header", "Header-Value"); 

       multipart.addFormField("description", "Cool Pictures"); 
       multipart.addFormField("keywords", "Java,upload,Spring"); 

       multipart.addFilePart("fileUpload", uploadFile1); 

       List<String> response = multipart.finish(); 

       System.out.println("SERVER REPLIED:"); 

       for (String line : response) { 
        System.out.println(line); 
       } 
      } catch (IOException ex) { 
       System.err.println(ex); 
      } 
     } 
} 
+0

ありがとうございました –

関連する問題