我已经在StackOverflow和谷歌上搜索过了,不幸的是我找不到答案。
我正在尝试通过"openConnection“获取我下载到android应用程序的文件的内容长度。文件下载正常,但我想要一个跟随进度的进度条。
为了达到这个目的,我需要得到content-length。
我的PHP文件中包含的头文件是:
$file_url = 'myfile.pdf';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header('Content-Length: '.filesize($file_url));
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);在联机检查HTTP标头时,我得到的结果是:
HTTP/1.1 200 OK =>
Date => Thu, 24 Jul 2014 10:34:04 GMT
Server => Apache/2
X-Powered-By => PHP/5.3.28
Content-Transfer-Encoding => Binary
Content-disposition => attachment; filename="myile.pdf"
Content-Length => 19011079
Vary => Accept-Encoding,User-Agent
Connection => close
Content-Type => application/octet-stream所以它确实返回了内容长度。
在整个过程中,fileSize int一直为-1,但文件已正确下载到我的下载目录中,所以这不是问题所在。
现在奇怪的是,当我将它直接设置为JPG时,它确实返回了"Content-Length“。以下是JPG的标头
HTTP/1.1 200 OK =>
Date => Thu, 24 Jul 2014 10:51:21 GMT
Server => Apache/2
Last-Modified => Thu, 24 Jul 2014 10:23:40 GMT
ETag => "506eae-10fcec-4feedd9b40300"
Accept-Ranges => bytes
Content-Length => 1113324
Connection => close
Content-Type => image/jpeg我尝试过的其他方法是直接链接到PDF,它也没有返回内容长度。我已经尝试上传较小的PDF的,在JPG大小的范围内,但没有成功。
发布于 2014-07-24 19:08:42
我不理解你的que..
在android中,你想获取content-length或者php文件
如果在php文件中,则使用以下代码
<?php
$url = 'http://www.google.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>试试下面的android java代码,这段代码很适合我。确保使用Apache HttpClient库。而且你不需要手动设置头部,为特定的请求生成头部是http的责任,如果你愿意,你可以改变头部数据。默认设置表头的所有成员字段。这是我的代码
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import validationUtility.Validation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends BaseActivity{
private TextView tvBreadCrum;
private static final String TAG = "Login.java";
/**
* content declaration
*/
private EditText etUserName, etPaddwd;
private TextView tvForgotPass;
private String uname, passwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState,R.layout.activity_login,getApplicationContext());
/**
* header field initialization
*/
tvBreadCrum = (TextView) findViewById(R.id.tv_bread_crumb);
tvBreadCrum.setText(">> Login");
/**
* content initialize
*
*/
etUserName = (EditText) findViewById(R.id.etUserEmail);
etPaddwd = (EditText) findViewById(R.id.etUserPassword);
tvForgotPass = (TextView) findViewById(R.id.tvForgotPass);
tvForgotPass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent genInquiry=new Intent(getApplicationContext(),ForgotPasswd.class);
startActivity(genInquiry);
}
});
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/* Inflate the menu; this adds items to the action bar if it is present. */
getMenuInflater().inflate(R.menu.contact_us, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.close) {
Toast.makeText(getApplicationContext(), "Good Bye...",
Toast.LENGTH_LONG).show();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void initVariableFields() {
uname = etUserName.getText().toString();
passwd = etPaddwd.getText().toString();
}
public boolean isValidate() {
initVariableFields();
boolean lbIsValid = true;
if (!Validation.isEmailAddress(etUserName, true)) {
return lbIsValid = false;
} else if (!Validation.hasText(etPaddwd, "Please your password", 5)) {
return lbIsValid = false;
}
return lbIsValid;
}
public void reset() {
etUserName.setText("");
etPaddwd.setText("");
}
public void onSendClick(View view) {
if (isValidate()) {
//Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_LONG).show();return;
new PostDataAsyncTask().execute();
reset();
}
}
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
private final ProgressDialog pDialog = new ProgressDialog(Login.this);
protected void onPreExecute() {
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Login.......");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected void onPostExecute(final String result) {
if (this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
runOnUiThread(new Runnable() {
public void run() {
reset();
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected String doInBackground(String... arg0) {
String responseStr = null;
try {
Log.v(TAG, "in Back job: "
+ "==========================Hello World");
String url1 = "http://lsrv.smartnet.cxm/kamleshG/Extra/postContactData/postData.php";
// the URL where the file will be posted
String postReceiverUrl = url1;
Log.v(TAG, "postURL: " + postReceiverUrl);
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient(httpParams);
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("email", new StringBody(uname));
reqEntity.addPart("passwd", new StringBody(passwd));
reqEntity.addPart("submitMessage", new StringBody(
"AndroidSubmit"));
httpPost.setEntity(reqEntity);
/* httpPost.setEntity(new UrlEncodedFormEntity(reqEntity)); */
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
System.out.println("Printing Response Header...\n");
Header[] headers = response.getAllHeaders();
//it prints whole header with content-length
for (Header header : headers) {
Log.v(TAG,"Key : " + header.getName()
+ " ,Value : " + header.getValue());
}
System.out.println("\n Done");
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
}
} catch (Exception e) {
Log.e("e.getClass().getName()", "" + e.toString());
}
return responseStr;
}
}
} 尝试此链接http://www.mkyong.com/java/how-to-get-http-response-header-in-java/
https://stackoverflow.com/questions/24931764
复制相似问题