我已经在StackOverflow上搜索并在Google上搜索,不幸的是我找不到答案。
我试图获取文件的内容长度,我通过" openConnection"下载到Android应用程序。文件正在下载确定,但我想要一个跟踪进度的进度条。
为了达到这个目的,我需要获得内容长度。
我在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也没有返回Content-Length。我已经尝试上传较小的PDF文件,但在JPG尺寸范围内也没有成功。
答案 0 :(得分:0)
我不理解你的阙..
在android中你想得到内容长度或在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/