Android : How to take make and HTTP GET in android from ajax using new URLConnection

on Monday, April 13, 2015


I've noticed that HtppClient has been deprecated and I want to update an old project and I am starting another new project, so I would like to not use deprecated code. Could someone show me the new way to do this in Android using URLConnection? I am at a little bit of a loss. Any improvements on my methods that I currently use in java are welcome. Thanks in advance.


I mostly have ajax commands in javascript that work and want to create these in android java. (API 22+).


Ajax code:



$.ajax({
url: 'http://myurl/app_login.php',
dataType: 'jsonp',
data: {email:myEmail, password:myPassword},
success: function(data) {
callback(data);
},
error: function(data) {
callback(data);
}
})


What I Used To Do:



final boolean myfunction(String user){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getString(R.string.authorization_url));
String body;
body = "email=" + user;

post.setHeader("Content-type","application/x-www-form-urlencoded");

try {
post.setEntity(new StringEntity(body,"UTF-8"));
try {
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
try {
JSONObject finalResult = new JSONObject(json);

//do stuff with final result

return finalResult.getBoolean("success");
} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}


Relevant Imports for Code Above:



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


Bonus Question seeking answer: I would greatly appreciate it if someone should show me the preferred way to do something like I do below since I upload a file. Sadly a lot of these methods/functions are now deprecated. This is similiar to the above question, but I do a file upload and wait for the finally() part of the try{}:


File Upload Code:



public String sendUploadFilePOST(FileData fileData, String acc, long parity){

//setup variables
String rqid = "FAILED";
String boundary = "----------------------" + System.currentTimeMillis();
File thisFile;
//setup http post
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getString(R.string.uploadHandler_url));
HttpResponse response;
post.addHeader("Content-type", "multipart/form-data; boundary=" + boundary);
post.addHeader("Accept","*/*");
post.addHeader("Accept-Encoding", "gzip, deflate");
post.addHeader("Cache-Control", "no-cache");
try {

File tempOutputDir = this.getCacheDir();
thisFile = new File(tempOutputDir, fileData.fileName);
OutputStream outputStream = new FileOutputStream(thisFile);
IOUtils.copy(getContentResolver().openInputStream(fileData.androidUri), outputStream);
outputStream.close();

fileData.sizeInBytes = thisFile.length();

//create multipartentity
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.setBoundary(boundary);
//add file
entityBuilder.addBinaryBody("doc", thisFile);
//add content values
entityBuilder.addTextBody("acc", acc);
entityBuilder.addTextBody("parity", 500000 + "");

//setup entity
HttpEntity myMultiEntity = entityBuilder.build();
post.setEntity(myMultiEntity);

//execute post
response = client.execute(post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return rqid;
} catch (ClientProtocolException e) {
e.printStackTrace();
return rqid;
} catch (IOException e) {
e.printStackTrace();
return rqid;
} finally {
//client.getConnectionManager().shutdown();
String doNothing = "";
}


try {
//process the response
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
rqid = reader.readLine();

//--to-do-- think of something if the file wasn't able to be deleted
boolean fileDeleted = thisFile.delete();

} catch (IOException e) {
e.printStackTrace();
}

//return rqid value if it is FAILED then the try did not complete fully
return rqid;
}


Relevant Imports:



import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;


Thanks in advance. Sorry for the overload of code, but just replicate the ajax if you can. I am just showing what I used to do and want to change.


0 comments:

Post a Comment