通过Apache中的HTTP客户端连接到Prestashop
问题描述:
我试图通过Apache的httpclient将图像上传到prestashop,但是当我执行我的脚本时,出现HTTP/1.1 401 Unauthorized错误。 我希望你能帮助我。非常感谢你。通过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());
}
答
解决:
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());
}