【发布时间】:2018-03-13 12:03:16
【问题描述】:
当我调用 Web 服务时,它会响应 403 和一些类似这样的响应数据。
{
"code": "[jwt_auth] invalid_email",
"message": "Dummy MEssage",
"data": {
"status": 403
}
}
我的代码如下所示
final AsyncTask<Void, String, String> waitForCompletion = new AsyncTask<Void, String, String>() {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
//Show Progress
}
@Override
public synchronized String doInBackground(Void... params) {
String res = "";
String charset = "UTF-8";
String requestURL = "www.myurl.com";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("username", email);
multipart.addFormField("password", password);
List<String> response = multipart.finish();
for (String line : response) {
System.out.println(line);
res = line;
Log.d("Message" , "Obtained" + response);
}
} catch (IOException ex) {
System.err.println(ex);
dismissProgressDialog(progressDialog);
}
return res;
}
@Override
protected void onPostExecute(String result) {
dismissProgressDialog(progressDialog);
if (hasValue(result)) {
UserLogin response = (new Gson()).fromJson(result, new TypeToken<UserLogin>() {
}.getType());
if (result.contains("message")) {
// Show error message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
showMessageAlert(Html.fromHtml(response.getMessage(), Html.FROM_HTML_MODE_COMPACT), getString(R.string.app_name), LoginActivity.this);
} else {
showMessageAlert(Html.fromHtml(response.getMessage()), getString(R.string.app_name), LoginActivity.this);
}
} else {
setUserId(LoginActivity.this , String.valueOf(response.getUserId()));
setToken(LoginActivity.this, response.getToken());
setLoginInformation(LoginActivity.this, result);
Intent intent = new Intent(LoginActivity.this, PickSportsActivity.class);
startActivity(intent);
finish();
}
}
}
};
问题是当我收到 403 和 404 错误作为响应时,如何获得响应。即使出现这些错误,我如何才能获取得到的响应。
这是我的多部分代码
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
StringBuilder result;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
* @param requestURL
* @param charset
* @throws IOException
*/
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.addRequestProperty("TOKEN", "Zml0c29vOmZpdHNvb0Aj");
// httpConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// httpConn.addRequestProperty("content-type", "application/x-www-form-urlencoded");httpConn.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=utf-8");
/* httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");*/
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
result = new StringBuilder();
boolean first = true;
if (first)
first = false;
else
result.append("&");
try {
result.append(URLEncoder.encode(name, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Adds a upload file section to the request
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
try {
result.append(URLEncoder.encode(fieldName, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Adds a header field to the request.
* @param name - name of the header field
* @param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
}
else if(status==500){
throw new IOException("Server HTTP_INTERNAL_ERROR : " + status);
}else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
【问题讨论】:
-
也发布你的 multipartutility 类。
-
嗨,我已经添加了我的 Multipart 代码
标签: java android web-services android-asynctask