I am using the following code to download file and calculate the length but the return value(length) is always -1
private long getContentLength(String url) {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
System.out.println("Content length was: " + httpEntity.getContentLength() + " and code: " + httpResponse.getStatusLine().getStatusCode());
return httpEntity.getContentLength();
}
The file being downloaded:
boolean download100MBFile() {
getContentLength("http://cachefly.cachefly.net/100mb.test");
return true;
}
The HTTP response code is: 200
The file gets downloaded from the browser, so there is no issue with the file. What is going wrong here?
The comment by Victor sparked me to use a stream.
Here is the updated code which works:
private long getContentLength(String url) {
outputStream.reset();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024 * 1024 * 1024);
try {
httpEntity.writeTo(outStream);
} catch (IOException ex) {
logException(ex);
return -1;
}
return outStream.size();
}
Related
I wrote a programm that can up-/download documents to sharepoint and check them in/out. It is used for data integration purposes and works quite well.
It was implemented using SOAP, but unfortunately the Server is configured to only be able to handle files with a size lesser than 50MB via SOAP.
The server configuration is fixed, so I have to work around that.
I added some code and I am able to up/download bigger files now, but If I want to check them in via SOAP I get the same error.
Now I wonder If it is possible to checkin/out files using the httpclient.
My code so far...
public class HttpClient {
private static final Logger LOGGER = LogManager.getLogger(HttpClient.class.getName());
HttpClient() {
}
public static void download(final String source, final File resultingFile) {
CloseableHttpClient client = WinHttpClients.createSystem();
HttpGet httpRequest = new HttpGet(source);
CloseableHttpResponse httpResponse = null;
try {
httpResponse = client.execute(httpRequest);
HttpEntity entity = httpResponse.getEntity();
if(httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
LOGGER.warn(httpResponse.getStatusLine());
}else {
LOGGER.debug(httpResponse.getStatusLine());
FileUtils.touch(resultingFile);
InputStream is = entity.getContent();
File outFile = new File(resultingFile.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(outFile);
int inByte;
while ((inByte = is.read()) != -1) {
fos.write(inByte);
}
is.close();
fos.close();
client.close();
}
} catch (ClientProtocolException e) {
LOGGER.warn(e);
} catch (UnsupportedOperationException e) {
LOGGER.warn(e);
} catch (IOException e) {
LOGGER.warn(e);
}
}
public static void upload(final File source, final String destination) {
CloseableHttpClient httpclient = WinHttpClients.createSystem();
HttpPut httpRequest = new HttpPut(destination);
httpRequest.setEntity(new FileEntity(new File(source.getPath())));
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpRequest);
EntityUtils.consume(httpResponse.getEntity());
if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
LOGGER.debug(httpResponse.getStatusLine());
LOGGER.info("Upload of " + source.getName() + " via HTTP-Client succeeded.");
} else if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
LOGGER.debug(httpResponse.getStatusLine());
}else {
LOGGER.warn("Uploading " + source.getName() + " failed.");
LOGGER.warn(httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
}
} catch (IOException e) {
LOGGER.warn(e);
LOGGER.warn(e.getMessage());
}
return;
}
}
Hey guys im trying to insert some data into a database from an android app, but the app crashes when trying to do so, i have the error log, but cant quite seem to figure out what it does. Can anyone please help me?
This is the error log: https://pastebin.com/Z8HmE21T
This is the code: https://pastebin.com/pCWaFniC
And this is my json parser
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;
Hello I have this code from Androidhive:
It works well but I want to install a timeout - because sometimes if there is low connection it is loading for minutes so the app is crashing at the and (asynctask). so my question: how can I install a timeout into the following code? Let's say it shall timeout after 10 seconds?
thank u
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 am using this code to POST and GET data from MySQL database .
However when getting data that is not in English, it is displayed as question marks ?
what changes do I make to enable Hebrew language use ?
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method == "POST"){
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"){
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
Make sure your HTTP response comes out encoded in Unicode (UTF-8 for example), and also your client (the application consuming the service) must be aware that of that encoding to read your response.
I am creating httpClient and when I send httpPost method, how can I attach a body to the httpRequest ??
public String httpPost(String URL, String BODY) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try {
response = httpclient.execute(httpPost); // get response from executing client
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
body.append(statusLine + "\n");
HttpEntity e = response.getEntity();
String entity = EntityUtils.toString(e);
body.append(entity);
} else {
body.append(statusLine + "\n");
// System.out.println(statusLine);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return body.toString();
}
For example, the string is
" < html > < header > Header < /header> < body> I am body < /body> "
Where do I attach that string to the request message ?
Thank you :)
You can create a StringEntity, set it to the HttpPost object, and set the correct Content-Type:
StringEntity entity = new StringEntity("data=" + java.net.URLEncoder.encode(body, "utf-8"));
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
And then send your POST request as usual.
Have you tried httpPost.setEntity(" < html > < header > Header < /header> < body> I am body < /body> ") before your try-catch?
I'm not entirely sure what "entity" refers to, but that's the best I can come up with from looking at the documentation here