use of org.apache.http.impl.client.DefaultRedirectHandler in project iNaturalistAndroid by inaturalist.
the class INaturalistService method request.
private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated, boolean useJWTToken, boolean allowAnonymousJWTToken) throws AuthenticationException {
DefaultHttpClient client = new DefaultHttpClient();
// Handle redirects (301/302) for all HTTP methods (including POST)
client.setRedirectHandler(new DefaultRedirectHandler() {
@Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
boolean isRedirect = super.isRedirectRequested(response, context);
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return isRedirect;
}
});
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, getUserAgent(mApp));
// Log.d(TAG, String.format("%s (%b - %s): %s", method, authenticated,
// authenticated ? mCredentials : "<null>",
// url));
HttpRequestBase request;
Log.d(TAG, String.format("URL: %s - %s (%s)", method, url, (params != null ? params.toString() : "null")));
if (method.equalsIgnoreCase("post")) {
request = new HttpPost(url);
} else if (method.equalsIgnoreCase("delete")) {
request = new HttpDelete(url);
} else if (method.equalsIgnoreCase("put")) {
request = new HttpPut(url);
} else {
request = new HttpGet(url);
}
// POST params
if (jsonContent != null) {
// JSON body content
request.setHeader("Content-type", "application/json");
StringEntity entity = null;
try {
entity = new StringEntity(jsonContent.toString(), HTTP.UTF_8);
} catch (UnsupportedEncodingException exc) {
exc.printStackTrace();
}
if (method.equalsIgnoreCase("put")) {
((HttpPut) request).setEntity(entity);
} else {
((HttpPost) request).setEntity(entity);
}
} else if (params != null) {
// "Standard" multipart encoding
Charset utf8Charset = Charset.forName("UTF-8");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int i = 0; i < params.size(); i++) {
if (params.get(i).getName().equalsIgnoreCase("image") || params.get(i).getName().equalsIgnoreCase("file") || params.get(i).getName().equalsIgnoreCase("user[icon]")) {
// If the key equals to "image", we use FileBody to transfer the data
String value = params.get(i).getValue();
if (value != null)
entity.addPart(params.get(i).getName(), new FileBody(new File(value)));
} else {
// Normal string data
try {
entity.addPart(params.get(i).getName(), new StringBody(params.get(i).getValue(), utf8Charset));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "failed to add " + params.get(i).getName() + " to entity for a " + method + " request: " + e);
}
}
}
if (method.equalsIgnoreCase("put")) {
((HttpPut) request).setEntity(entity);
} else {
((HttpPost) request).setEntity(entity);
}
}
if (url.startsWith(API_HOST) && (mCredentials != null)) {
// For the node API, if we're logged in, *always* use JWT authentication
authenticated = true;
useJWTToken = true;
}
if (authenticated) {
if (useJWTToken && allowAnonymousJWTToken && (mCredentials == null)) {
// User not logged in, but allow using anonymous JWT
request.setHeader("Authorization", getAnonymousJWTToken());
} else {
ensureCredentials();
if (useJWTToken) {
// Use JSON Web Token for this request
request.setHeader("Authorization", getJWTToken());
} else if (mLoginType == LoginType.PASSWORD) {
// Old-style password authentication
request.setHeader("Authorization", "Basic " + mCredentials);
} else {
// OAuth2 token (Facebook/G+/etc)
request.setHeader("Authorization", "Bearer " + mCredentials);
}
}
}
try {
mResponseErrors = null;
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String content = entity != null ? EntityUtils.toString(entity) : null;
Log.d(TAG, String.format("RESP: %s", content));
JSONArray json = null;
mLastStatusCode = response.getStatusLine().getStatusCode();
switch(response.getStatusLine().getStatusCode()) {
// switch (response.getStatusCode()) {
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
// Validation error - still need to return response
Log.e(TAG, response.getStatusLine().toString());
case HttpStatus.SC_OK:
try {
json = new JSONArray(content);
} catch (JSONException e) {
Log.d(TAG, "Failed to create JSONArray, JSONException: " + e.toString());
try {
JSONObject jo = new JSONObject(content);
json = new JSONArray();
json.put(jo);
} catch (JSONException e2) {
Log.d(TAG, "Failed to create JSONObject, JSONException: " + e2.toString());
}
}
mResponseHeaders = response.getAllHeaders();
try {
if ((json != null) && (json.length() > 0)) {
JSONObject result = json.getJSONObject(0);
if (result.has("errors")) {
// Error response
Log.e(TAG, "Got an error response: " + result.get("errors").toString());
mResponseErrors = result.getJSONArray("errors");
return null;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if ((content != null) && (content.length() == 0)) {
// In case it's just non content (but OK HTTP status code) - so there's no error
json = new JSONArray();
}
return json;
case HttpStatus.SC_UNAUTHORIZED:
throw new AuthenticationException();
case HttpStatus.SC_GONE:
Log.e(TAG, "GONE: " + response.getStatusLine().toString());
// or post them as new observations
default:
Log.e(TAG, response.getStatusLine().toString());
}
} catch (IOException e) {
// request.abort();
Log.w(TAG, "Error for URL " + url, e);
}
return null;
}
Aggregations