如何发送带有字符串和字节数组参数的post请求



我需要在post请求中发送一个字节数组。我正在尝试使用截击,但我只知道如何发送只有字符串参数的帖子。具体来说,我需要在请求中填写以下字段:

params.add(new BasicNameValuePair("Id", ""));
params.add(new BasicNameValuePair("Empresa", "1"));
params.add(new BasicNameValuePair("Matricula", "1"));
params.add(new BasicNameValuePair("Foto", bytearray[] here));  << this is the field that need byte array
params.add(new BasicNameValuePair("Data", "11/22/2020 16:30:00"));
params.add(new BasicNameValuePair("GPS", "0"));
params.add(new BasicNameValuePair("idDispositivo", "0"));
params.add(new BasicNameValuePair("arquivo", ""));
params.add(new BasicNameValuePair("face", "0"));
params.add(new BasicNameValuePair("ip", "0.0"));

我知道上面的方法不起作用。这只是我如何填写职位申请的一个例子。

我在C#中看到了这个答案:使用HttpClient将字节数组发布到Web API服务器。我需要Java中类似的东西。

用Base64字符串编码字节数组并不能解决我的问题。

我接受任何能解决我问题的方法,我不需要专门用凌空抽射来做帖子请求。

PS.:抱歉我英语不好。

我找到了解决问题的方法。我把字节数组编码成Base64字符串是错误的。我认为这不起作用,因为我当时在凌空抽射,但没有起作用。

但我发现了一个带有JSON的post方法,它确实有效。这是张贴方法:

public void novoPost(String empresa, String matricula, byte[] foto, String data, String face) throws IOException {
URL url = new URL("http://myurl.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String jsonInputString = "{"Id":" + """ + "" +  """ +  "," +
""Empresa":" + """ + empresa +  """ + "," +
""Matricula":" + """ + matricula +  """ + "," +
""Foto":" + """ + getStringImage(foto) +  """ + "," +
""Data":" + """ + data +  """ + "," +
""GPS":" + """ + getGPS() +  """ + "," +
""idDispositivo":" + """ + getIMEI() +  """ + "," +
""arquivo":" + """ + "" +  """ + "," +
""face":" + """ + face +  """ + "," +
""ip":" + """ + getIPAddress(true) +  """ + "," +
"}";
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}

这就是将字节数组编码为String:的方法

public String getStringImage(byte[] bm) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
String encode = android.util.Base64.encodeToString(bm, Base64.DEFAULT);
return encode;
}

最新更新