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);
Related
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");
I am really in pain right now please help me solve this issue.
I've previously also tried to make the http request to my localhost and it all works fine but right now it is not working and I don't know why.
I am trying to make the request from the following code.
HttpClient httpclient = new DefaultHttpClient();
String result="";
try
{
HttpPost httppost = new HttpPost("http://[ip]/php/untitled.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email",this.userEmail));
nameValuePairs.add(new BasicNameValuePair("pwd",this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
if(entity!=null)
{
InputStream inputStream=entity.getContent();
result= convertStreamToString(inputStream);
}
}
catch (ClientProtocolException e)
{
Log.e("errorhai",e.getMessage());
}
catch (IOException e)
{
Log.e("errorhai",e.getMessage());
}
return result;
I've also added the internet permission but still it keeps saying
Connect to [ip] timed out.
When I enter the url in my browser it works fine but it is not working here.Please tell me what can be the causes of this problem ?
you can set the time out parameter to handle such type of exception :
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 = 60*1000*1;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
/* Set the default socket timeout (SO_TIMEOUT)
in milliseconds which is the timeout for waiting for data. */
int timeoutSocket = 60*1000*1;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
//HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
/** Finally, we send our request using HTTP. This is the synchronous
long operation that we need to run on this thread. */
httpResponse = client.execute(request);
/*int responseCode = httpResponse.getStatusLine().getStatusCode();
String message = httpResponse.getStatusLine().getReasonPhrase();*/
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String res = convertStreamToString(instream);
MLog.v("HTTP RESPONSE : ", "Res :-"+res);
if(!res.trim().equalsIgnoreCase("[]")){
response.setResult(res);
response.setSuccess(true);
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.RECORD_NOT_FOUND);
}
/** Closing the input stream will trigger connection release */
instream.close();
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
}
catch (Exception e) {
//client.getConnectionManager().shutdown();
e.printStackTrace();
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
//you can again try to send request , if your response is not sucess.
//retryHttpRequestIfNotSucess();
your problem might be related to the login. Is your script expecting a preemptive authetification? Do you have a error page for a failed login?
For requesting a page with preemptive http basic authentication i'm using the following code that is working. Have a try, if its working for you too.
DefaultHttpClient httpclient = null;
HttpParams params = new BasicHttpParams();
HttpResponse response = null;
HttpEntity entity = null;
// Set connection parameter
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
httpclient = new DefaultHttpClient(params);
// Create a post statement
HttpPost httppost = new HttpPost(Constants.urlLogin);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
httppost.getParams().setParameter("http.protocol.single-cookie-header", true);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("login_name", this.username));
nvps.add(new BasicNameValuePair("login_passwd", this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httppost);
entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String loadedContent = null;
if (entity != null)
{
loadedContent = EntityUtils.toString(entity, HTTP.UTF_8);
// loadedContent =
// Helper.convertStreamToString(entity.getContent());
entity.consumeContent();
}
if (statusCode != (HttpStatus.SC_OK))
{
throw new ServerCommunicationErrorException();
} else if (!loadedContent.contains("Logout"))
{
// Login failed
throw new LoginFailedException();
}
As you can see, i get a "not logged in" page as result, if the login fails to determine the login process. Further more i set some parameters, that might be also interesting for you. You can look here for more information on parameters.
I am uploading a large string to web-service. The string contains new line character which is written as "\n".
The data looks some thing like:
05/06/2012 11:35:43 AM- DB exists, transferring data\n05/06/2012
11:48:20 AM- loadUserSpinners, cursor.getCount()=2\n05/06/2012
11:48:20 AM- Battery: 50%\n05/06/2012 11:48:20 AM- ITEM SELECTED: 0
the above data is stored in string JsonArrObj. To upload the data/string, i am using the following code:
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 360000; //6 minutes
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 420000; //7 minutes
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
JSONArray jsonParams = new JSONArray();
Object[] params={IPAddress,Database,DbName,DbPassword,JsonArrObj};
for (int i = 0; i < params.length; i++) {
jsonParams.put(params[i]);
}
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("id", Id);
jsonRequest.put("method", FunctionName);
jsonRequest.put("params", jsonParams);
JSONEntity entity = new JSONEntity(jsonRequest);
entity.setContentType("application/json; charset=utf-8");
HttpPost request = new HttpPost(URL);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity httpEntity = response.getEntity();
InputStream content = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content,"iso-8859-1"),8);
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
LogE("result line: "+line);
String str=convertString(line);
parseJson(str);
}
content.close();
}
The string is uploaded successfully. The problem I am facing is: while string is being converted to jsonParams, the "\n" in the string data gets converted to "\\n" as a result, on the server side, it shows a small box in stead of new line.
When I open this string in NOTEPAD application, it displays small boxes. But when I open it in WORDPAD app, text is displayed on a new line. According to me, I might have entered in-correct "content-type" or encoding. Please suggest a solution for the same.
JsonArrObj= URLEncoder.encode(JsonArrObj, "utf-8"); gave error while uploading itself...
The data which is sent in the jsonParams- jsonArrObj finally looks like:
05\/06\/2012 04:05:52 PM- DB exists, transferring
data\\n05\/06\/2012 04:32:56 PM- loadUserSpinners,
cursor.getCount()\\u003d2\\n05\/06\/2012 04:32:56 PM- Battery:
50%\\n05\/06\/2012 04:32:56 PM- ITEM SELECTED: 0
Well, the encoder escapes your newline characters. If you want to transport newline chars properly, you can encode the whole stream with base64. If your target os (for data to send) is Windows then you should use \r\n, if mac then \r if unix\linux then \n. After encoding data try to send the encoded and decode it on the other side. For base64 Mr. Google will convince you.
Hey why don't you use the Unicode values for \n as and any other character that is creating this problem
like this U+002FU+006E
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
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;