【发布时间】:2015-08-11 05:23:47
【问题描述】:
我正在尝试发送带有一些字符串参数的POST request 和jpeg image file。整个代码在IntentService。
我正在为基本auth 使用 Authorization 标头(凭据在将它们与其他 Web 服务一起使用时有效)。
我真的不知道出了什么问题,也许是请求属性有问题。请记住,我正在发送字符串,但也发送图像。
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
URL url = new URL(urlServer);
String credentials = "test@test.com"+":"+"testtest";
final String basicAuth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", basicAuth);
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setInstanceFollowRedirects(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("imei="+ getImei()
+ "&id=38"
+ "&type = b"
+ "&step=1"
+ "&image="
);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
int sentBytes = 0;
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
mBuilder.setProgress(100,(int) (sentBytes * 100 / bytesAvailable),false);
mNotifyManager.notify(1, mBuilder.build());
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
sentBytes += bufferSize;
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
mBuilder.setContentText("Upload complete");
mBuilder.setProgress(0, 0, false);
mNotifyManager.notify(1, mBuilder.build());
fileInputStream.close();
outputStream.flush();
outputStream.close();
if(connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP){
url = new URL(connection.getHeaderField("Location"));
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Authorization", basicAuth);
}
InputStreamReader isr = null;
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
String line = "";
isr = new InputStreamReader(
connection.getInputStream());
reader = new BufferedReader(isr);
line = reader.readLine();
while (line != null) {
sb.append(line);
try {
line = reader.readLine();
}catch (Exception e){
line = null;
}
}
String a;
a = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
【问题讨论】:
-
尝试使用 DefaultHttpClient
-
401 错误不一定是因为您发送的用户名或密码错误。也可能是因为编码错误。
标签: android httpurlconnection basic-authentication intentservice unauthorized