I am trying to update the database on server but there seems to be some problem with the code. Code goes to the catch block and Toast with message of null is displayed.
public class Test extends AppCompatActivity {
static String inputLine, data = "";
HttpURLConnection conn = null;
String q = "update data set room='ANKUSH' where id='5'";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
try {
URL url = new URL("http://takeyourtime.16mb.com/postdb.php");
String agent = "Applet";
String q2 = "insert into user(name,username,password,email) values('AHA','xxxAA','xxxA','xSDxx')";
String query = "query=" + q2;
String type = "application/x-www-form-urlencoded";
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", agent);
conn.setRequestProperty("Content-Type", type);
conn.setRequestProperty("Content-Length", "" + query.length());
OutputStream out = conn.getOutputStream();
out.write(query.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((inputLine = in.readLine()) != null) {
data = data + inputLine + "\n";
}
//data = StringParser.StringPars(data);
in.close();
int rc = conn.getResponseCode();
System.out.print("Response Code = " + rc + "\n");
String rm = conn.getResponseMessage();
System.out.print("Response Message = " + rm + "\n");
Toast.makeText(this, "Response Code = " + rc + "\n", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage() + "\n" + e.getCause(), Toast.LENGTH_SHORT).show();
} finally {
conn.disconnect();
}
}
}
1) Add <uses-permission android:name="android.permission.INTERNET" /> to your manifest
2) Android blocks network connections from main thread.
Related
I'm using a Service in different process of my app using android:process=":MyService" and I recognized that my AsyncTasks in MyService class doesn't work and execute, so how can I sync my datas with my Server in MyService class?
I just want to update my Server from this class cause it's a ForegroundService that should be active most of the times. I believe that defining MyService class as a separate process helps my app's battery usage. I've already defined an inner class and used it inside MyService class but it doesn't work at all, I also tried to use another custom asyncTask class Object in MyService class but it doesn't work either
here's an example of my code in MyService class:
static class UpdatePoint extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... strings) {
String userId = user.get(SessionManager.getKeyId()).toString();
String coin = strings[1];
String step = strings[2];
String log_lat = strings[3];
String log_lng = strings[4];
String log_zone = strings[5];
String log_address = strings[6];
//Log.d("updatePoint","coin:"+coin+", step:"+step);
try {
String update_point_url = "http://mohregroup.ir/db-mapapa/updatePoint.php";
URL url = new URL(update_point_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5*1000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("userId", "UTF-8") + "=" + URLEncoder.encode(userId, "UTF-8")
+ "&" + URLEncoder.encode("coin", "UTF-8") + "=" + URLEncoder.encode(coin, "UTF-8")
+ "&" + URLEncoder.encode("step", "UTF-8") + "=" + URLEncoder.encode(step, "UTF-8")
+ "&" + URLEncoder.encode("log_lat", "UTF-8") + "=" + URLEncoder.encode(log_lat, "UTF-8")
+ "&" + URLEncoder.encode("log_lng", "UTF-8") + "=" + URLEncoder.encode(log_lng, "UTF-8")
+ "&" + URLEncoder.encode("log_zone", "UTF-8") + "=" + URLEncoder.encode(log_zone, "UTF-8")
+ "&" + URLEncoder.encode("log_address", "UTF-8") + "=" + URLEncoder.encode(log_address, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
//Log.d("updatePoints response:", response.toString().trim());
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Timber.d("done Successfully!");
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
and using it inside another method of MyService class :
if (getAddress() != null) {
if (getAddress().getFeatureName() == null &&
getAddress().getAddressLine(0) != null) {
new UpdatePoint().execute(String.valueOf(coins),
String.valueOf(steps),
String.valueOf(originLocation.getLatitude()),
String.valueOf(originLocation.getLongitude()),
getAddress().getFeatureName(), "not titled");
} else if (getAddress().getFeatureName() != null &&
getAddress().getAddressLine(0) == null) {
new UpdatePoint().execute(String.valueOf(coins),
String.valueOf(steps),
String.valueOf(originLocation.getLatitude()),
String.valueOf(originLocation.getLongitude()),
"not titled", getAddress().getAddressLine(0));
} else {
new UpdatePoint().execute(String.valueOf(coins), String.valueOf(steps),
String.valueOf(originLocation.getLatitude()), String.valueOf(originLocation.getLongitude()),
getAddress().getFeatureName(), getAddress().getAddressLine(0));
}
} else {
new UpdatePoint().execute(String.valueOf(coins), String.valueOf(steps),
String.valueOf(originLocation.getLatitude()), String.valueOf(originLocation.getLongitude()),
"not titled", "not titled");
}
So, any Ideas about
how to use an asyncTask in a service with different process?
or
any other way in order to update the server from a service with different process?
any helps would be appreciated a lot!
Thanks.
One way could be using timer and when timer is finished you can call asynctask and reset the timer again.
I have tried relentlessly to create a succesfull file upload from my JAVA/Android project to Django/Python backend.
The file I am trying to upload is a wav audio file which is stored on the phone.
I am trying to mix two sets of code.
The Android code I am using is the one taken from: How to upload a WAV file using URLConnection.
public class curlAudioToWatson extends AsyncTask<String, Void, String> {
String asrJsonString="";
#Override
protected String doInBackground(String... params) {
String result = "";
try {
Log.d("Msg","**** UPLOADING .WAV to ASR...");
URL obj = new URL(ASR_URL);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df");
conn.setRequestProperty("Content-Type", "audio/wav");
conn.setRequestProperty("enctype", "multipart/form-data");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String wavpath=mRcordFilePath;
File wavfile = new File(wavpath);
boolean success = true;
if (wavfile.exists()) {
Log.d("Msg","**** audio.wav DETECTED: "+wavfile);
}
else{
Log.d("Msg","**** audio.wav MISSING: " +wavfile);
}
String charset="UTF-8";
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
OutputStream output=null;
PrintWriter writer=null;
try {
output = conn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
byte [] music=new byte[(int) wavfile.length()];//size & length of the file
InputStream is = new FileInputStream (wavfile);
BufferedInputStream bis = new BufferedInputStream (is, 16000);
DataInputStream dis = new DataInputStream (bis); // Create a DataInputStream to read the audio data from the saved file
int i = 0;
copyStream(dis,output);
}
catch(Exception e){
}
conn.connect();
int responseCode = conn.getResponseCode();
Log.d("Msg","POST Response Code : " + responseCode + " , MSG: " + conn.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","***ASR RESULT: " + response.toString());
JSONArray jresponse=new JSONObject(response.toString()).getJSONObject("Recognition").getJSONArray("NBest");
asrJsonString=jresponse.toString();
for(int i = 0 ; i < jresponse.length(); i++){
JSONObject jsoni=jresponse.getJSONObject(i);
if(jsoni.has("ResultText")){
String asrResult=jsoni.getString("ResultText");
//ActionManager.getInstance().addDebugMessage("ASR Result: "+asrResult);
Log.d("Msg","*** Result Text: "+asrResult);
result = asrResult;
}
}
Log.d("Msg","***ASR RESULT: " + jresponse.toString());
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","POST FAILED: " + response.toString());
result = "";
}
} catch (Exception e) {
Log.d("Msg","HTTP Exception: " + e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Log.d("Msg","onPostEXECUTE SUCCESS, consuming result");
//sendTextInputFromUser(result);
//ActionManager.getInstance().addDebugMessage("***ASR RESULT: "+asrJsonString);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}else{
Log.d("Msg","onPostEXECUTE FAILED" );
}
}
}
public void copyStream( InputStream is, OutputStream os) {
final int buffer_size = 4096;
try {
byte[] bytes = new byte[buffer_size];
int k=-1;
double prog=0;
while ((k = is.read(bytes, 0, bytes.length)) > -1) {
if(k != -1) {
os.write(bytes, 0, k);
prog=prog+k;
double progress = ((long) prog)/1000;///size;
Log.d("Msg","UPLOADING: "+progress+" kB");
}
}
os.flush();
is.close();
os.close();
} catch (Exception ex) {
Log.d("Msg","File to Network Stream Copy error "+ex);
}
}
The Django backend code is taken from: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html and I am using the simple upload:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'core/simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'core/simple_upload.html')
I have already disabled the need for CSRF using #csrf_exempt.
I am getting the error "MultiValueDictKeyError" since Java does not post the file with the name 'myfile' for request.FILES['myfile'] to catch. Is have tried removing the ['myfile'] and just use request.FILES but then I get an error on
filename = fs.save(myfile.name, myfile)
saying there is no name to fetch.
Can I post the file so that it it catched by
request.FILES['myfile']
or is there better/simpler Django backend-code to use for communication with Android/IOS.
Thanks in advance and I apologize if this is a stupid question but I am dead stuck.
Here I go again answering my own question.
I found the following code from Android:How to upload .mp3 file to http server?
Using that instead of How to upload a WAV file using URLConnection and changing the line: dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
To dos.writeBytes("Content-Disposition: form-data; name=\"myfile\";filename=\"" + existingFileName + "\"" + lineEnd);
fixed my problem.
Always getting the Bad Request error, error code - 400. Using commons-codec-1.10 jar file but its not available for native Android. here is my code
Date date = new java.util.Date();
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String timestamp = dateFormat.format(date);
String httpVerb = "POST";
String path = "/v1/sms/" + "+918003059919";
String contentType = "application/json";
String canonicalizedHeaders = "x-timestamp:" + timestamp;
String body = "{\"message\":\"" + "Hiiii" + "\"}";
byte[] data = md5Digest(body);
String contentMd5 = Base64.encodeToString(data, 0, data.length,
Base64.DEFAULT);
String stringToSign = httpVerb + "\n" + contentMd5 + "\n"
+ contentType + "\n" + canonicalizedHeaders + "\n"
+ path;
String signature = signature(SinchService.APP_SECRET,
stringToSign);
String authorization = "Application " + SinchService.APP_KEY
+ ":" + signature;
URL url = new URL("https://messagingApi.sinch.com" + path);
HttpsURLConnection connection = (HttpsURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type",
"application/json");
connection.setRequestProperty("x-timestamp", timestamp);
connection.setRequestProperty("authorization", Base64.encodeToString(authorization.getBytes(),Base64.DEFAULT));
OutputStream os = connection.getOutputStream();
os.write(body.getBytes());
StringBuilder response = new StringBuilder();
int status = connection.getResponseCode();
System.out.println("resonse code: "+status);
InputStream iresponse = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
Using android.util.Base64 package to encode but not its not working.
Sinch applications are not automatically whitelisted for sending SMS. Contact them at dev#sinch.com to get your app whitelisted.
I am trying to make an API call to get a list of YouTube videos like this:
#Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
final String key = "my_key";
final String channelId = "UCoLEarNS6E-Kbzoya_p7k2Q";
String charset = "UTF-8";
String response = null;
try
{
String query = String.format("key=%s&channelId=%s&part=snippet,id&order=date&maxResults=20",
URLEncoder.encode( key, charset ) ,
URLEncoder.encode( channelId, charset )
);
final URL url = new URL( myUrl + "?" + query );
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
final InputStream is = conn.getInputStream();
final byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1)
{
builder.append(new String(buffer, 0, readCount));
}
response = builder.toString();
}
catch (IOException e)
{
sendEmail ( "MyQuestionsActivity Network Error" , "Error: " + e.getMessage() );
}
return response;
}
But it keeps erroring out. And if I paste the url into the browser, it returns some JSON. But in this case, the sendEmail utility I made is sending me this error from e.getMessag():
Error: https://www.googleapis.com/youtube/v3/search?key=my_key&channelId=UCoLEarNS6E-Kbzoya_p7k2Q&part=snippet,id&order=date&maxResults=20
Would anyone know what isn't going right? Also I am having some issues with my catLog so I am not able to see the exception.
How to send file in POST-query using Apache HTTPComponents?
One possible solution is to generate HTTP headers by yourself, as explained here - http://en.wikipedia.org/wiki/MIME (see "Multipart messages")
I wrote such function. Maybe it is not well-written, but it works great.
private static final String REQUEST_BOUNDARY = "somethingUniqueForYourQuery";
private static String sendRequest(String url, String method, String params, File file, String fileField) {
HttpURLConnection httpConn = null;
StringBuilder httpContent = new StringBuilder();
String lineEnd = "\r\n";
String twoHyphens = "--";
byte[] fileContent = new byte[0];
int fileSize = 0;
// trying to read file
if (file != null) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
httpContent.append(twoHyphens + REQUEST_BOUNDARY + lineEnd);
httpContent.append("Content-Disposition: form-data; name=\"" + fileField + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
httpContent.append(lineEnd);
fileSize = fileInputStream.available();
fileContent = new byte[fileSize];
fileInputStream.read(fileContent, 0, fileSize);
fileInputStream.close();
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
}
// trying to perform request
try {
httpConn = (HttpURLConnection) new URL(url).openConnection();
if (httpConn != null) {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setConnectTimeout(CONNECTION_TIMEOUT_STRING);
httpConn.setRequestMethod(method);
if (file != null && httpContent.length() > 0) {
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + REQUEST_BOUNDARY);
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
if (params != null) {
dos.writeBytes(params);
}
dos.writeBytes(httpContent.toString());
dos.write(fileContent, 0, fileSize);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + REQUEST_BOUNDARY + twoHyphens + lineEnd);
dos.flush();
dos.close();
}
else if (params != null) {
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(params);
out.close();
}
httpConn.connect();
int response = httpConn.getResponseCode();
BufferedReader rd;
if (httpConn.getErrorStream() == null) {
rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
}
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
if (rd != null) {
rd.close();
}
return sb.toString();
} else {
Log.d(DEBUG_TAG, "Connection Error");
}
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
return null;
}