我在使用以下代码将图像上传到使用 Java 的 imageshack 时遇到问题。我得到的响应是 http 拒绝我的连接。我认为我的问题在于我如何提供图像文件,因为我不确定它是否应该是 base64、byteArray 等。
任何帮助都会很棒,谢谢。
public String ImageShack (String imageDir, String myKey) {
//set file
BufferedImage image = null;
File file = new File(imageDir);
//Set namevalue pairs
List<NameValuePair> params = new ArrayList<NameValuePair>();
try
{
image = ImageIO.read(file);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
ImageIO.write(image, "png", byteArray);
byte[] byteImage = byteArray.toByteArray();
String dataImage = new Base64().encodeAsString(byteImage);
//Assign name valued pars
params.add(new BasicNameValuePair("key", myKey));
params.add(new BasicNameValuePair("fileupload", dataImage));
params.add(new BasicNameValuePair("format", "json"));
//Create HTTPClient and Client
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.imageshack.us/upload_api.php");
//set entities
httpPost.setEntity(new UrlEncodedFormEntity(params));
//Execute & get response
HttpResponse response = httpClient.execute(httpPost);
return response.toString();
}
catch(Exception e)
{
return "Error: " + e.getMessage();
}
}