Get content of a file, throws "host name may be null" - android

I'm having a trouble getting the content of a file located at a address similar to
"http:///127.0.0.1:1935/app/unique_id/file.txt". The exception states that the host name
may be null. I think the problem is due to the port.
How do I get the content of the file?
final HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
final DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
InputStream inputStream = timedCall(new Callable<InputStream>() {
public InputStream call() throws Exception {
HttpResponse response = httpClient.execute(httpGet);
return response.getEntity().getContent();
};
}, 10, TimeUnit.SECONDS);
return inputStream;

It looks like you have one too many slashes after the "http:" in the example URL you provided. There should only be two, as in:
http://127.0.0.1:1935/app/unique_id/file.txt

Related

How to set connection timeout for volley?

I know volley have a Retry Policy,but what i know , this is for a socket timeout,not for a connection timeout, Apache HttpClient have setConnectionTimeout and setSoTimeout Method,is anyone know if i want to set connection timeout for volley framework.
you must open the HttpClientStack under package com.android.volley.toolbox; and then at the body of function performRequest you can change the values of
HttpConnectionParams.setConnectionTimeout(httpParams, your time);
HttpConnectionParams.setSoTimeout(httpParams, your time);
hope it helps.
If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use setParams().
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
// after this set the parameters
httpClient.setParams(httpParameters);
Refer this:
How to set HttpResponse timeout for Android in Java

How to pass header to WebView in Android [duplicate]

This question already has answers here:
Send Post request along with HttpHeaders on Android
(2 answers)
Closed 2 years ago.
I am passing post data as Json using postUrl() to WebView in Android. Now I want to pass a header "Content-Type: application/json" also along with that. How to achieve it?
may this will help u :)
HttpPost httpPost = new HttpPost(url_src);
HttpParams httpParameters = new BasicHttpParams();
httpclient.setParams(httpParameters);
StringEntity se = new StringEntity(str,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
httpPost.setHeader("userId", ""+userId);//userID
httpPost.setHeader("machineId", machineId);//deviceUserMachineID
response = httpclient.execute(httpPost);
I believe this will help: link
Doesn't look like you can actually send headers with postUrl(), only with loadUrl() method.
it possible to post data with header i have done it in my project
I am posting you my code ...
HttpParams par = new BasicHttpParams();
//par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(par, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(par, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(par);
// httpClient.setParams(par);
HttpPost httpPost = new HttpPost(url);
httpPost = new HttpPost(url);
if(postMessage==null)
throw new IllegalArgumentException("please send post data as well");
byte[] data =postMessage.toString().getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
System.out.println("Base64: "+base64);
// httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setEntity(new StringEntity(base64));
httpPost.setHeader("token", app.getToken());
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
System.out.println("httpEntity.getContent():"+ is );
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
data = sb.toString();
//remember httpconnection should be in background thread
// if you use asynchtask then upper code should be in doinbackground method
//and in onpostexecution do data load in webview
webview.loadData(data, "text/html","UTF-8");

JSON String too Large for StringEntity

In my app I turn an image into a bas64 string and add it to a JSON object to send to the server. The problem seems to be that the string is too large? Originally I was getting an out of Memory error now the response just returns null and Ive debugged it to the point where I have found it to be that the String I pass to my StringEntity Object is too large. I have read alot of other answers but none have worked or they just don't quite apply to what I need to do. The Code is as follows
#Override
protected String doInBackground(JSONArray... params) {
JSONObject allPostObj = new JSONObject();
try {
allPostObj.put("receiptImgs", params[0]);
//Log.e("in obj Try" , allPostObj.toString());
DefaultHttpClient httpClient = new DefaultHttpClient();
// WCF service path
HttpPost httpPost = new HttpPost("http://localhost/path");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpPost.setParams(httpParameters);
StringEntity se = new StringEntity(allPostObj.toString());
Log.e("DEBUGGING",allPostObj.toString());
se.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String readLine = reader.readLine();
Log.d("DEBUG RESPONSE",readLine);
JSONObject jsonResponse = new JSONObject(readLine);
answer = jsonResponse.getString("saveImageResult");
Log.e("returning", answer);
}
And replacing the line
StringEntity se = new StringEntity(allPostObj.toString());
With:
StringEntity se = new StringEntity("{\"receiptImgs\":[{\"imgString\":\"\",\"imgPath\":\"test\"}]}");
Works just fine
Any ideas will be greatly appreciated
You should not use StringEntity for large content, you should switch to FileEntity or InputStreamEntity, depending on where you store your data.
quick fix you may try (not compiled/tested):
InputStream stream = new ByteArrayInputStream(allPostObj.toString().getBytes("UTF-8"));
InputStreamEntity entity = new InputStreamEntity(stream , -1);

Android: Is there a way to set a timeout for response = httpclient.execute(httppost);

I'm trying to load information over the network on a thread. When there is no internet it will freeze for a long time before setting off a exception or just freeze.
Is there a way to set a timeout for // FREEZES HERE or takes a long time to through exception when there is no internet?
Is their a way to set a timeout for response = httpclient.execute(httppost);?
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://besttechsolutions.biz/projects/bookclub/getevents.php");
// FREEZES HERE or takes a long time to through exception when there is no internet
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
Try the following.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
if(null == httpClient)
httpClient = new DefaultHttpClient(httpParameters);
The above code generally sets a default timeout for httpClient. To check internet access, refer the link posted by Nomand.

Exception to be handled for HttpConnection

Kindly provide me the code for handling the HttpConnection or related Exceptions & how to display that to the user.
Specifically , I would like to know how to handle TimeOut for HttpConnection & how to display that alert to the user.
Kindly provide the same code.
Here's the code
HttpPost hPost = new HttpPost(url);
StringEntity se = new StringEntity(envelope,HTTP.UTF_8);
hPost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(hPost);
HttpEntity entity = httpResponse.getEntity();
return entity;

Categories

Resources