2016-07-28 14 views
0

Apacheのhttpclientを介してprestashopに画像をアップロードしようとしていますが、スクリプトを実行するとHTTP/1.1 401 Unauthorizedというエラーが発生します。 私があなたを助けてくれることを願っています。どうもありがとうございました。JavaでApache HTTPクライアント経由でPrestashopに接続

private void addImg(String imgURL, int productId) throws Exception { 


    URL imgUrl = new URL(imgURL); 
    InputStream is = imgUrl.openStream(); 

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
    int nRead; 
    byte[] data = new byte[16384]; 

    while ((nRead = is.read(data, 0, data.length)) != -1) { 
     buffer.write(data, 0, nRead); 
    } 
    buffer.flush(); 

    String completeUrlString = URLSTRING + "/api/images/products/" + String.valueOf(productId); 

    CredentialsProvider credsProvider = new BasicCredentialsProvider(); 
    credsProvider.setCredentials(
      new AuthScope("localhost/prestashop", 80), 
      new UsernamePasswordCredentials("XV4J9MNC1WPMCDMAAXJ1MRMCEAT9DJDJ", "")); 
    CloseableHttpClient httpclient = HttpClients.custom() 
      .setDefaultCredentialsProvider(credsProvider) 
      .build(); 

    HttpPost httppost = new HttpPost(completeUrlString); 
    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
    builder.addPart("image", new ByteArrayBody(buffer.toByteArray(), "upload.jpg")); 

    HttpEntity entity = builder.build(); 
    httppost.setEntity(entity); 

    CloseableHttpResponse response = httpclient.execute(httppost); 
    System.out.println(response.getStatusLine()); 
} 

答えて

0

は解決済み:

private void addImg(String imgURL, int productId) throws Exception { 


    URL imgUrl = new URL(imgURL); 
    InputStream is = imgUrl.openStream(); 

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
    int nRead; 
    byte[] data = new byte[16384]; 

    while ((nRead = is.read(data, 0, data.length)) != -1) { 
     buffer.write(data, 0, nRead); 
    } 
    buffer.flush(); 

    String completeUrlString = URLSTRING + "/api/images/products/" + String.valueOf(productId); 

    CredentialsProvider credsProvider = new BasicCredentialsProvider(); 
    credsProvider.setCredentials(
      AuthScope.ANY, 
      new UsernamePasswordCredentials("XV4J9MNC1WPMCDMAAXJ1MRMCEAT9DJDJ", "")); 
    CloseableHttpClient httpclient = HttpClients.custom() 
      .setDefaultCredentialsProvider(credsProvider) 
      .build(); 

    HttpPost httppost = new HttpPost(completeUrlString); 
    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
    builder.addPart("image", new ByteArrayBody(buffer.toByteArray(), "img.jpg")); 

    HttpEntity entity = builder.build(); 
    httppost.setEntity(entity); 

    HttpResponse response = httpclient.execute(httppost); 
    System.out.println(response.getStatusLine()); 
} 
関連する問題