2016-07-28 17 views
0

Ich versuche Bilder auf Prestashop über httpclient von Apache hochzuladen, aber wenn ich mein Skript ausführen, habe ich einen Fehler von HTTP/1.1 401 Unauthorized. Ich hoffe, dass Sie mir helfen können. Vielen Dank.Verbinden mit Prestashop über Apache HTTP-Client in Java

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()); 
} 

Antwort

0

Entschlossen:

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()); 
}