I'm trying to download file from URL using HttpURLConnection
in Android.
First I added textviews programmatically and set a listener to each textviews to download a file. Below is that code.
for(Element ele: elements){
final TextView attachItem = new TextView(this);
attachItem.setText("myStr");
attachItem.setTag("myStr2");
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
attachItem.setLayoutParams(llp);
ll.addView(attachItem, i++);
// set a listener to textview
attachItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// when clicked, execute class that extends `AsyncTask`
new downloadAttach().
execute(attachItem.getTag().toString(), attachItem.getText().toString());
}
});
}
And downloadAttach()
downloads a file from server using http protocol. Below is code.
HttpURLConnection con = (HttpURLConnection)(new URL("MyUrl")).openConnection();
con.setRequestMethod("POST");
...
...
...
con.setRequestProperty("Cookie", "myCookie");
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes("myQuery");
output.close();
InputStream is = con.getInputStream();
FileOutputStream fos = new FileOutputStream(new File(Environment.getDataDirectory(), "fileName"));
// In my case, getDataDirectory() returns "/data"
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
But when I click a textview, nothing changes. There isn't a file in /data
directory in my phone.
What's the problem? Someone please help.