【发布时间】:2014-11-18 20:37:05
【问题描述】:
我正在尝试使用 http get 请求将 png 发送到服务器。我正在使用下面的代码。
字符串编码(在客户端):
byte[] bytes = Files.readAllBytes(Paths.get(chosenFile.getPath()));
String image = new String(bytes, "ISO-8859-1");
然后我使用字符串图像向服务器发送 http get 请求。
服务器收到它,但我得到的图像与我发送的图像不同(我无法打开我收到的图像)。我正在使用URLEncoder.encode(image, "ISO-8859-1") 对http get 请求的url 进行编码。当我使用URLEncoder.encode(image, "UTF-8") 时,也会发生同样的情况。
为什么这不起作用? 有没有更好的方法来做这种事情?
UPD #0
图片发送代码:
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser= new JFileChooser();
int choice = chooser.showOpenDialog(this);
if (choice != JFileChooser.APPROVE_OPTION) return;
File chosenFile = chooser.getSelectedFile();
try {
byte[] bytes = Files.readAllBytes(Paths.get(chosenFile.getPath()));
String image = new String(bytes, "ISO-8859-1");
if(image != null){
boolean allsent = false;
long k = 0;
String query = "0";
while(!allsent){
String s = image;
String send = "";
long q;
if(k+400>image.length()){
q=image.length();
allsent=true;
}
else q = k+400;
for(long i=k;i<q;i++)
send+=s.charAt((int) i);
System.out.println(send);
String response = new HTTP().GET(Constants.ADDRESS_ADDIMAGE
+ "?" + Constants.USERNAME + "=" + URLEncoder.encode(user, "UTF-8")
+ "&" + Constants.IMAGE + "=" + URLEncoder.encode(send, "ISO-8859-1")
+ "&" + Constants.QUERY + "=" + URLEncoder.encode(query, "UTF-8"));
k+=400;
query="1";
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
注意: HTTP().GET() 调用标准的 http get。
UPD #1 服务器代码
@GET
@Path("/addimage")
@Produces(MediaType.APPLICATION_JSON)
public String addImage(@QueryParam("username") String uname, @QueryParam("image") String image, @QueryParam("query") String query) {
if(query.equals("0")){
String s = image;
JDBC.addImage("ABase", "MarketLogin", "image", uname, s);
}
else{
String s = JDBC.selectDB("ABase", "MarketLogin", "image", uname, "username") + image;
JDBC.addImage("ABase", "MarketLogin", "image", uname, s);
}
return "1";
}
注意:
JDBC 是用于更新 mysql DB 的类。服务器期待由ISO-8859-1 编码的字符串。
【问题讨论】:
-
为什么要发送字符串?发送字节。
-
你能解释一下怎么做吗?
-
如果您在发送图像时遇到问题,请包含发送图像的代码! (不仅仅是读取它的代码)。此外,图像绝对不是用“ISO-8859-1”编码的!
-
您需要以适合您发送的图像的 mime 类型发送内容。它不是一个字符串,试图把它当作一个字符串是行不通的。
-
我们需要更多地了解 Web 服务器的期望。从您的代码中,它似乎期望图像数据作为查询参数中的编码字符串。这可能是真的,但非常非常奇怪。因此,请指出 Web 服务器如何需要图像的定义
标签: java string encode http-get