[英]Connect to Prestashop through Apache http client in java
我正在嘗試通過Apache的httpclient將圖像上傳到prestashop,但是當我執行腳本時,出現HTTP / 1.1 401 Unauthorized錯誤。 我希望你能幫助我。 非常感謝你。
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());
}
解決:
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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.