Why does second http request is always null? - java

When I do http request in the PoolData(), request returns with data, and in AccoutData is always null.
In debugger, if I wait 1-2 sec after PoolData(), next request - returns not null. Method oder doesn't metter. Why is that, and how can I wait for 2nd request?
public void onClick(View v) {
new PoolData().execute();
}
private class PoolData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dataPool.clear();
}
#Override
protected Void doInBackground(Void... arg0) {
PoolData();
AccoutData();
return null;
}
private void PoolData(){
HttpHandler sh = new HttpHandler();
String statsBrowser = "http://api.electroneum.space/v1/stats/nonBrowser";
String browserStr = sh.makeServiceCall(statsBrowser);
//parsing...
}
private void AccoutData(){
HttpHandler sh = new HttpHandler();
String statsAddress = "http://api.electroneum.space/v1/stats/address/" + settings.getString(lp, "n/a");
String addressStr = sh.makeServiceCall(statsAddress);
//parsing...
}
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
Log.e(TAG, "Responce: " + response);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.toString());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
12-14 14:27:18.941 6624-6651/dev.flair.the.electroneumspacepool
I/OpenGLRenderer: Initialized EGL, version 1.4
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Get enable program binary service property (1)
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Initializing program atlas...
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Program binary detail: Binary length is 169916, program map length is 152.
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Succeeded to mmap program binaries. File descriptor is 54, and path is /dev/ashmem .
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: No need to use file discriptor anymore, close fd(54).
12-14 14:27:18.979 6624-6624/dev.flair.the.electroneumspacepool W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
12-14 14:27:19.035 6624-6651/dev.flair.the.electroneumspacepool W/MALI: glDrawArrays:714: [MALI] glDrawArrays takes more than 5ms here. Total elapse time(us): 10394
12-14 14:27:23.448 6624-6672/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.452 6624-6672/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo: api.electroneum.space get result from proxy >>
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool I/System.out: propertyValue:true
12-14 14:27:23.459 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [CDS]connect[api.electroneum.space/104.27.156.123:80] tm:90
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 14:27:23.612 6624-6672/dev.flair.the.electroneumspacepool E/HttpHandler: MalformedURLException: java.io.BufferedInputStream#3d6a54f5
12-14 14:27:23.613 6624-6672/dev.flair.the.electroneumspacepool I/NetworkManagementSocketTagger: untagSocket(56)
12-14 17:08:49.897 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: Responce:
{"stats":{"data...."}}
12-14 17:08:49.899 19931-20613/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.900 19931-20613/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: IOException: java.io.FileNotFoundException: http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/MainActivity: Response from browser: null

Related

Download and save PDF on sdcard not found

I'm trying to download a pdf from an url and then save and read it. But I get the error java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource. when I try to read it. Any idea ?
Here is my Downloader class :
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the line to download and read the pdf :
String extStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "menu.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", file);
PdfReader reader = new PdfReader(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/menu.pdf");
Here is the error :
05-02 13:59:01.138 16747-16747/? I/art: Not late-enabling -Xcheck:jni (already on)
05-02 13:59:01.139 16747-16747/? W/art: Unexpected CPU variant for X86 using defaults: x86
05-02 13:59:01.676 16747-16747/com.example.yohannmbp.ematoufaire I/InstantRun: starting instant run server: is main process
05-02 13:59:01.868 16747-16747/com.example.yohannmbp.ematoufaire W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
05-02 13:59:02.440 16747-16787/com.example.yohannmbp.ematoufaire D/NetworkSecurityConfig: No Network Security Config specified, using platform default
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire I/OpenGLRenderer: Initialized EGL, version 1.4
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 1
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 0
05-02 13:59:03.029 16747-16747/com.example.yohannmbp.ematoufaire W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
05-02 13:59:11.011 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.IOException: No such file or directory
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.File.createNewFile(File.java:948)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:106)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.FileNotFoundException: /storage/emulated/0/pdf/menu.pdf (No such file or directory)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.open(Native Method)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.Downloader.DownloadFile(Downloader.java:18)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:110)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.088 16747-16752/com.example.yohannmbp.ematoufaire I/art: Do partial code cache collection, code=30KB, data=29KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: After code cache collection, code=23KB, data=25KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: Increasing code cache capacity to 128KB
05-02 13:59:11.127 16747-16747/com.example.yohannmbp.ematoufaire I/System.out: java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource.
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
**strong text** #Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(AppConstant.BASE_URL + URLEncoder.encode(sUrl[0], "UTF-8"));
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
fileName = sUrl[0].substring(sUrl[0].lastIndexOf("/") + 1,
sUrl[0].length());
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context, "Download error: File is not Found.", Toast.LENGTH_LONG).show();
else {
new AlertDialog.Builder(context)
//.setTitle("Delete entry")
.setMessage("File Downloaded Successfully. Do you want to open it?")
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "There is no app registered to handle the type of file selected.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
}
try this
downloadTask = new DownloadTask();
downloadTask.execute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", "", "");
private class DownloadTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ll_view.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
File sourcePath = Environment.getExternalStorageDirectory();
File path = new File(sourcePath + "/" + Constants.DIR_NAME + "/");
path.mkdir();
File file = new File(path, "/ecute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf");
if (file.exists()) {
file.delete();
}
output = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ll_view.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(final Integer... values) {
super.onProgressUpdate(values);
// Log.e("progressing", "" + values[0]);
// edt_search.setText("" + values[0]);
// new Thread(new Runnable() {
// public void run() {
progressBar.setProgress(values[0]);
// tv_downloading.setText("" + values[0] + "%");
// }
// }).start();
}
#Override
protected void onCancelled(String s) {
super.onCancelled(s);
}
#Override
protected void onCancelled() {
super.onCancelled();
}
}
if your target and compile sdk higher than lolipop then you have to add request permission code before download refer this link and read and write external storage permission required

The api isApiSupported return true but SipManager newInstance still return null in Android native Sip

I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282) 
at android.app.ActivityThread.access$600(ActivityThread.java:147) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5265) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 
at dalvik.system.NativeStart.main(Native Method) 

java.io.IOException: Post failed with error code 403 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i tried to post values from android mobile to my web server. i am getting 403 error with java.io.exception.
this is my logcat messages
[CDS]connect[local.test.com/192.99.166.230:80] tm:90
04-30 12:57:07.388 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:07.413 10416-10416/gcm.androidexample.com.ravi V/InputMethodManager﹕ onWindowFocus: null softInputMode=288 first=true flags=#1810100
04-30 12:57:07.413 10416-10416/gcm.androidexample.com.ravi D/InputMethodManager﹕ deactivate the inputconnection in ControlledInputConnectionWrapper.
04-30 12:57:07.413 10416-10416/gcm.androidexample.com.ravi V/InputMethodManager﹕ START INPUT: com.android.internal.policy.impl.PhoneWindow$DecorView{41cd4600 V.E..... R.....ID 0,0-480,800} ic=null tba=android.view.inputmethod.EditorInfo#41cfca48 controlFlags=#104
04-30 12:57:07.416 10416-10416/gcm.androidexample.com.ravi V/InputMethodManager﹕ Starting input: Bind result=InputBindResult{com.android.internal.view.IInputMethodSession$Stub$Proxy#41cfd2d8 com.android.inputmethod.latin/.LatinIME #186}
04-30 12:57:07.513 10416-10416/gcm.androidexample.com.ravi D/OpenGLRenderer﹕ Flushing caches (mode 0)
04-30 12:57:07.696 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:36222] connected
04-30 12:57:07.696 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:07.820 10416-10416/gcm.androidexample.com.ravi D/OpenGLRenderer﹕ Flushing caches (mode 0)
04-30 12:57:08.012 10416-10434/gcm.androidexample.com.ravi D/AndroidRuntime﹕ zoneinfo:Asia/Calcutta
04-30 12:57:08.014 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[36222]
04-30 12:57:08.015 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:36222]
04-30 12:57:08.015 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 1:java.io.IOException: Post failed with error code 403
04-30 12:57:08.015 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Sleeping for 2401 ms before retry
04-30 12:57:10.416 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #2 to register
04-30 12:57:10.418 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:10.418 10416-10434/gcm.androidexample.com.ravi E/URL﹕ >
04-30 12:57:10.425 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕ getaddrinfo: local.test.com get result from proxy >>
04-30 12:57:10.426 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:10.426 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][1] connection local.test.com/192.99.166.230:80;LocalPort=34236(0)
04-30 12:57:10.427 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ /192.99.166.230:80] tm:90
04-30 12:57:10.427 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:10.460 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.33, dur:3015.55, max:3015.55, min:3015.55
04-30 12:57:10.733 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:34236] connected
04-30 12:57:10.733 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:11.045 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[34236]
04-30 12:57:11.046 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:34236]
04-30 12:57:11.046 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 2:java.io.IOException: Post failed with error code 403
04-30 12:57:11.047 10416-10434/gcm.androidexample.com.ravi D/GCM Android xample﹕ Sleeping for 4802 ms before retry
04-30 12:57:15.849 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #3 to register
04-30 12:57:15.873 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:15.885 10416-10434/gcm.androidexample.com.ravi E/URL﹕ >
04-30 12:57:15.889 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.18, dur:5428.43, max:5428.43, min:5428.43
04-30 12:57:15.889 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] this:0x52c45438, api:1, last queue time elapsed:5428.43
04-30 12:57:15.891 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕ getaddrinfo: local.test.com get result from proxy >>
04-30 12:57:15.891 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:15.892 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][2] connection local.test.com/192.99.166.230:80;LocalPort=44926(0)
04-30 12:57:15.892 10416-10434/gcm.androidexample.com.ravi I/System.out﹕
04-30 12:57:15.893 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:16.202 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:44926] connected
04-30 12:57:16.202 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:16.503 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[44926]
04-30 12:57:16.504 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:44926]
04-30 12:57:16.504 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 3:java.io.IOException: Post failed with error code 403
04-30 12:57:16.505 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Sleeping for 9604 ms before retry
04-30 12:57:26.109 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #4 to register
04-30 12:57:26.140 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:26.145 10416-10434/gcm.androidexample.com.ravi E/URL﹕ >
I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.10, dur:10271.53, max:10271.53, min:10271.53
04-30 12:57:26.160 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] this:0x52c45438, api:1, last queue time elapsed:10271.53
04-30 12:57:26.162 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕ getaddrinfo: local.test.com get result from proxy >>
04-30 12:57:26.165 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:26.166 10416-10434/gcm.androidexample.com.ravi I/System.out﹕
04-30 12:57:26.166 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]connect[local.test.com/192.99.166.230:80] tm:90
04-30 12:57:26.174 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:26.492 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:45892] connected
04-30 12:57:26.492 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:26.806 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[45892]
04-30 12:57:26.806 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:45892]
04-30 12:57:26.807 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 4:java.io.IOException: Post failed with error code 403
04-30 12:57:26.807 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Sleeping for 19208 ms before retry
04-30 12:57:46.015 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #5 to register
04-30 12:57:46.044 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:46.051 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.05, dur:19890.52, max:19890.52, min:19890.52
04-30 12:57:46.051 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] this:0x52c45438, api:1, last queue time elapsed:19890.52
04-30 12:57:46.060 10416-10434/gcm.androidexample.com.ravi E/URL﹕ > http://local.test.com/gcmfile/register
04-30 12:57:46.065 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕
04-30 12:57:46.066 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:46.066 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][4] connection local.test.com/192.99.166.230:80;LocalPort=38220(0)
04-30 12:57:46.066 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]connect[local.test.com/192.99.166.230:80] tm:90
04-30 12:57:46.067 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:46.390 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:38220] connected
04-30 12:57:46.393 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:46.701 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[38220]
04-30 12:57:46.702 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:38220]
04-30 12:57:46.702 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 5:java.io.IOException: Post failed with error code 403
this is my code on register
package gcm.androidexample.com.ravi;
/**
* Created by Thidiff on 4/24/2015.
*/
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.PowerManager;
import android.util.Log;
import com.google.android.gcm.GCMRegistrar;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import gcm.androidexample.com.gcm.R;
public class Controller extends Application{
private final int MAX_ATTEMPTS = 5;
private final int BACKOFF_MILLI_SECONDS = 2000;
private final Random random = new Random();
// Register this account with the server.
void register(final Context context, String name, String email, final String regId) {
Log.i(Config.TAG, "registering device (regId = " + regId + ")");
String serverUrl = Config.YOUR_SERVER_URL;
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
params.put("name", name);
params.put("email", email);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
String res = "";
// Once GCM returns a registration id, we need to register on our server
// As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(Config.TAG, "Attempt #" + i + " to register");
try {
//Send Broadcast to Show message on screen
displayMessageOnScreen(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
// Post registration values to web server
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
//Send Broadcast to Show message on screen
String message = context.getString(R.string.server_registered);
displayMessageOnScreen(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(Config.TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(Config.TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(Config.TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
//Send Broadcast to Show message on screen
displayMessageOnScreen(context, message);
}
// Unregister this account/device pair within the server.
void unregister(final Context context, final String regId) {
Log.i(Config.TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = Config.YOUR_SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
displayMessageOnScreen(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the our server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
displayMessageOnScreen(context, message);
}
}
// Issue a POST request to the server.
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(Config.TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
// If response is not success
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
// Checking for all possible internet providers
public boolean isConnectingToInternet(){
ConnectivityManager connectivity =
(ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
// Notifies UI to display a message.
void displayMessageOnScreen(Context context, String message) {
Intent intent = new Intent(Config.DISPLAY_MESSAGE_ACTION);
intent.putExtra(Config.EXTRA_MESSAGE, message);
// Send Broadcast to Broadcast receiver with message
context.sendBroadcast(intent);
}
//Function to display simple Alert Dialog
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Set Dialog Title
alertDialog.setTitle(title);
// Set Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Set alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Set OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Show Alert Message
alertDialog.show();
}
private PowerManager.WakeLock wakeLock;
public void acquireWakeLock(Context context) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "WakeLock");
wakeLock.acquire();
}
public void releaseWakeLock() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
Error 403 in HTML is Forbidden, this means your server is not setup to accept xmlhttp or forum posts or you are using your service incorrectly.

Android Json HttpGet/Post HttpResponse

I am trying to take a product from mysql database according to its barcode number. I checked my php codes they are working but on android side i am taking an error.
Here my GetProductDetails class (i think this part is ok);
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Query_product extends Activity {
EditText txtId, txtName, txtPrice, txtDesc;
Button btnSave, btnDelete;
String ID = "";
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// url to get all products list
private static final String url_product_details = "http://10.0.2.2/ssa/get_product_details.php";
private static final String url_update_product = "http://10.0.2.2/ssa/update_product.php";
private static final String url_delete_product = "http://10.0.2.2/ssa/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "barcode";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.query_prod);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
ID += " " + getIntent().getExtras().getString(Constants.ID);
pid = ID;
new GetProductDetails().execute();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
class GetProductDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Query_product.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtId = (EditText) findViewById(R.id.inputId);
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtId.setText(product.getString(TAG_PID));
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}
else
{
String error = "Not found!";
Toast.makeText(Query_product.this, error, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
Here makeHttpRequest class;
public JSONObject makeHttpRequest (String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I couldn't be able to solve the problem. Program runs until this line;
HttpResponse httpResponse = httpClient.execute(httpGet);
Logcat errors;
12-14 18:05:30.994: E/AndroidRuntime(986): FATAL EXCEPTION: main
12-14 18:05:30.994: E/AndroidRuntime(986): android.os.NetworkOnMainThreadException
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.Socket.connect(Socket.java:842)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.JSONParser.makeHttpRequest(JSONParser.java:66)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.Query_product$GetProductDetails$1.run(Query_product.java:134)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.handleCallback(Handler.java:725)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Looper.loop(Looper.java:137)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-14 18:05:30.994: E/AndroidRuntime(986): at dalvik.system.NativeStart.main(Native Method)
12-14 18:10:31.483: I/Process(986): Sending signal. PID: 986 SIG: 9
12-14 18:10:33.372: D/gralloc_goldfish(1025): Emulator without GPU emulation detected.
You cannot perform network tasks on the main thread because it might block your application in case the network task takes a very long time. You need to run such tasks in the background using AsyncTask instead.
Here's the documentation.
Try using the below code inside your main activity below setContentView(), to avoid the networkOnmainThread exception..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Looks like the error is not of json.
You are trying to call a url from Main Thread which is not allowed from android 4.0
Try using AsynTask or call the url from secondary thread.

Android downloading a file getting a FileNotFoundException

else if (v.getId() == R.id.update) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File("/sdcard/"+"download/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"test.txt");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this code keeps coming out with the FileNotFoundException, but the file is there, if you follow the url you can see it.
does it have to be hosted in a specific way? or is it something wrong with the way im getting it
EDIT: this is the logcat message
12-14 22:29:19.890: W/System.err(24557): java.io.FileNotFoundException: http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt
12-14 22:29:19.890: W/System.err(24557): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
12-14 22:29:19.890: W/System.err(24557): at com.MasterZangetsu.kentrocksoc.MainActivity.onClick(MainActivity.java:99)
12-14 22:29:19.890: W/System.err(24557): at android.view.View.performClick(View.java:3591)
12-14 22:29:19.890: W/System.err(24557): at android.view.View$PerformClick.run(View.java:14263)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.handleCallback(Handler.java:605)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 22:29:19.895: W/System.err(24557): at android.os.Looper.loop(Looper.java:137)
12-14 22:29:19.895: W/System.err(24557): at android.app.ActivityThread.main(ActivityThread.java:4507)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-14 22:29:19.895: W/System.err(24557): at dalvik.system.NativeStart.main(Native Method)
12-14 22:29:20.170: W/WifiStateTracker(2010): getNetworkInfo : NetworkInfo: type: WIFI[], state: DISCONNECTED/DISCONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: false
comment the below piece of line in your code.
urlConnection.setDoOutput(true);

Categories