How to solve W/OkHttpClient: A connection was leaked? - java

I'm trying to create a connection to some remote server, and get the following warning in my LogCat: "W/OkHttpClient: A connection to "some url" was leaked. Did you forget to close a response body?"
Now I don't understand why is it happening.
I use Apache IO commons to count number of bytes sent and received, and it's the only use if mine with OkHTTP.
Can you please look at my code snippet and tell me what's wrong with it?
This is the code where I try to create a connection:
public static JSONObject getConfiguration(Context context) throws HttpRequestException {
long bytes = 0;
long netUsage = HttpUtils.getCurrentNetworkUsage(context);
int statusCode = 0, count = 0;
NetworkRequest.Status netStatus = NetworkRequest.Status.FAILED;
JSONObject commonInformation;
HttpURLConnection connection = null;
CountingInputStream cis = null;
InputStreamReader isr = null;
BufferedReader br = null;
InputStream is = null;
CountingOutputStream cos = null;
// result
JSONObject receivedConfig = null;
try {
commonInformation = ConfigurationProcessor.getCommonInformation(context);
if (commonInformation == null) {
return null;
}
URL url = new URL(BuildConfig.SERVER_CONFIG_URL);
if (BuildConfig.DEBUG) {
LogUtils.d(TAG, "url = " + url.getPath());
}
connection = url.getProtocol().equals("https")? getHttpsConnection(url) : getHttpConnection(url);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Encoding", "gzip");
byte[] gzipped = HttpUtils.gzip(commonInformation.toString());
cos = new CountingOutputStream(connection.getOutputStream());
cos.write(gzipped);
cos.flush();
statusCode = connection.getResponseCode();
switch (statusCode) {
case 200: {
// get the response
is = connection.getInputStream();
cis = new CountingInputStream(is);
isr = new InputStreamReader(cis);
br = new BufferedReader(isr);
StringBuilder builder = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
builder.append(output);
}
receivedConfig = new JSONObject(builder.toString());
netStatus = NetworkRequest.Status.SUCCEEDED;
break;
}
case 502: {
throw new HttpRequestException("Received 502 error (Bad Gateway)", NetworkRequest.Type.GET_REMOTE_CONFIGURATION);
}
}
// analytics about the request
if (BuildConfig.DEBUG) {
LogUtils.d(TAG, "generating analytics about the http request");
}
count = receivedConfig == null ? 0 : 1;
if (cis != null) {
bytes = cis.getByteCount();
}
if (cos != null) {
bytes += cos.getByteCount();
}
} catch (Exception | OutOfMemoryError ex) {
LogUtils.e(TAG, ex.getMessage());
ex.printStackTrace();
} finally {
closeStream(is);
closeStream(br);
closeStream(isr);
closeStream(cis);
closeStream(cos);
if (connection != null) connection.disconnect();
createNetworkRequest(context, statusCode, netUsage, netStatus, count, bytes, NetworkRequest.Type.GET_REMOTE_CONFIGURATION, BuildConfig.SERVER_CONFIG_URL);
}
if (BuildConfig.DEBUG) {
LogUtils.d(TAG, "Received configuration data");
}
return receivedConfig;
}

Related

Why the file I download via GitHub API has no content?

I am using the GitHub API to fetch files from a repository. I have the functionality implemented and it does work, I download the needed files but I found something strange, out of the 4 files I get, one is empty (no content inside) even though when I go the to repository and open it there it is clearly with content. The rest of the files have their content in when downloaded. Any idea why that happens?
Here is my code:
public int downloadFromGithub(String repo, String fileName) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", ****);
connection.setRequestProperty("Accept", ****);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK && fileName!=null)
{
return saveFile(connection, fileName);
}
else { return connection.getResponseCode();}
}
public void downloadMultipleFilesFromGithub(String repo,String directoryPath) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", *****);
connection.setRequestProperty("Accept", "***");
String response = getResponseBody(connection);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray array = jsonObj.getJSONArray("tree");
for (int i=0; i < array.length(); i++) {
System.out.println(array.getJSONObject(i).get("path"));
String path = array.getJSONObject(i).get("path").toString();
if(path.contains("Scripts")){
String fileName = path.replace(scriptsDirectoryReplace, "");
downloadFromGithub(scriptsRepositoryDirectory+fileName,fileName);
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String getResponseBody(HttpURLConnection conn) {
BufferedReader br = null;
StringBuilder body = null;
String line = "";
try {
br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
body = new StringBuilder();
while ((line = br.readLine()) != null)
body.append(line);
return body.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int saveFile(HttpURLConnection connection, String fileName) throws IOException {
// opens input stream from the HTTP connection
String saveFilePath = fileSaveDirectory + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream writer = new FileOutputStream(saveFilePath);
InputStream reader = connection.getInputStream();
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
reader.close();
writer.close();
return connection.getResponseCode();
}

Getting response code 400 when trying to get access token from Azure AD

I am implementing azure for my web application and trying to get access token by following there openId connect tutorial
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
And when i am requesting to get the access token, i am always getting bad request 400
Request to get access token :
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPl.......
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
here is my code :
public static String post( String endpoint,
Map<String, String> params) {//YD
StringBuffer paramString = new StringBuffer("");
//if(!Utilities.checkInternetConnection(context)){
// return XMLHandler.getXMLForErrorCode(context, JSONHandler.ERROR_CODE_INTERNET_CONNECTION);
//}
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
StringBuffer tempBuffer = new StringBuffer("");
String paramval;
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
if (param != null) {
if (paramString.length() > 0) {
paramString.append("&");
}
System.out.println( "post key : " + param.getKey());
String value;
try {
paramval = param.getValue();
if(paramval!=null)
value = URLEncoder.encode(paramval, "UTF-8");
else
value = "";
} catch (UnsupportedEncodingException e) {
value = "";
e.printStackTrace();
}
paramString.append(param.getKey()).append("=")
.append(value);
}
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(endpoint);
String data = "";
try {
// Add your data
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))
//httppost.addHeader("Host", host);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
if (!paramString.equals("")) {
if (tempBuffer.length() > 0) {
data = data + tempBuffer.toString();
}
data = data + paramString.toString();
if (data.endsWith("&")) {
data = data.substring(0, data.length() - 1);
}
httppost.setEntity(new ByteArrayEntity(data.getBytes()));
}
System.out.println( "post Stringbuffer : " + data);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int statuscode = response.getStatusLine().getStatusCode();
System.out.println("Response code : " + statuscode);
if (statuscode != 200) {
return null;
}
HttpEntity entity = response.getEntity();
InputStream in = null;
if (entity != null) {
in = entity.getContent();
}
if (in != null) {
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
String response2 = builder.toString();
System.out.println("response :" + response2);
retrycount = 0;
return response2;
}
}
catch(UnknownHostException e){
e.printStackTrace();
return null;
}
catch (EOFException eof) {
if (retrycount < max_retry) {
eof.printStackTrace();
post( endpoint, params);
retrycount = 1;
}
} catch (Throwable th) {
throw new IOException("Error in posting :" + th.getMessage());
}
retrycount = 0;
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Please help me with this
Thanks in Advance
Have you ensured the redirect uri passed to /token is the same as the one you passed to /authorize
I believe, it will help if you can test the OAuth auth code flow with your current client id, secret and scope using Postman tool in order to rule out bad configuration.
Please refer to the code below to request AuthorizationCode.
public static void getAuthorizationCode() throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId
+ "&response_type=" + reponseType
+ "&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F"
+ "&response_mode=query"
+ "&resource=https%3A%2F%2Fgraph.windows.net"
+ "&state=12345";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Then you could get access token using the AuthorizationCode you got and get refresh code using the code below.
public static void getToken(String refreshToken) throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
+ "&grant_type=refresh_token&resource=https%3A%2F%2Fgraph.windows.net";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Hope it helps you.

How to get form data from POST request in Java

How to I extract form data from a POST request eg. $ curl -X POST -d asdf=blah http://localhost:8000/proxy/http://httpbin.org/post - and I need to extract asdf=blah.
The way I am currently doing it relies heavily on the data I have read being in a certain format (I am assuming the form data is always on the last line). Is there a better (and/or simpler) way to get the data which does not depend on the format of the data being read ?
(Note: the proxy deals with both GET and POST requests)
Here is code I have written :
public class ProxyThread3 extends Thread {
private Socket clientSocket = null;
private OutputStream clientOutputStream;
private static final int BUFFER_SIZE = 32768;
public ProxyThread3(Socket socket) {
super("ProxyThread");
this.clientSocket = socket;
}
public void run() {
try {
clientOutputStream = clientSocket.getOutputStream();
// Read request
InputStream clientInputStream = clientSocket.getInputStream();
byte[] b = new byte[8196];
int len = clientInputStream.read(b);
String urlToCall = "";
if (len > 0) {
String userData = new String(b, 0, len);
String[] userDataArray = userData.split("\n");
//Parse first line to get URL
String firstLine = userDataArray[0];
for (int i = 0; i < firstLine.length(); i++) {
if (firstLine.substring(i).startsWith("http://")) {
urlToCall = firstLine.substring(i).split(" ")[0];
break;
}
}
//get request type
String requestType = firstLine.split(" ")[0];
String userAgentHeader = "";
//get USER-AGENT Header and Accept Header
for (String data : userDataArray) {
if (data.startsWith("User-Agent")) {
userAgentHeader = data.split(":")[1].trim();
break;
}
}
switch (requestType) {
case "GET": {
sendGetRequest(urlToCall, userAgentHeader);
break;
}
case "POST": {
String postParams = null;
//Get Form Data
if (!userDataArray[userDataArray.length - 1].isEmpty()) {
postParams = userDataArray[userDataArray.length - 1];
}
sendPostRequest(urlToCall, userAgentHeader, postParams);
break;
}
}
} else {
clientInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendPostRequest(String urlToCall, String userAgentHeader, String postParams) throws IOException {
URL urlToWriteAndReadFrom = new URL(urlToCall);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlToWriteAndReadFrom.openConnection();
httpURLConnection.setRequestMethod("POST");
// set User-Agent header
httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);
httpURLConnection.setDoOutput(true);
OutputStream urlOutputStream = httpURLConnection.getOutputStream();
if (postParams != null) {
urlOutputStream.write(postParams.getBytes());
urlOutputStream.flush();
}
urlOutputStream.close();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream dataReader = httpURLConnection.getInputStream();
//begin send response to client
byte inputInBytes[] = new byte[BUFFER_SIZE];
assert dataReader != null;
int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
while (index != -1) {
clientOutputStream.write(inputInBytes, 0, index);
index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
}
clientOutputStream.flush();
}
}
private void sendGetRequest(String urlToCall, String userAgentHeader) throws IOException {
URL urlToReadFrom = new URL(urlToCall);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlToReadFrom.openConnection();
// set True since reading and getting input
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
// set User-Agent header
httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream dataReader = httpURLConnection.getInputStream();
//begin send response to client
byte inputInBytes[] = new byte[BUFFER_SIZE];
assert dataReader != null;
int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
while (index != -1) {
clientOutputStream.write(inputInBytes, 0, index);
index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
}
clientOutputStream.flush();
}
}
}
PS. I am new to all of this so if there are any errors in my code, please do point them out
Here is a full example on how to create a Java HTTP server that handles POST and GET requests.
https://www.codeproject.com/Tips/1040097/Create-a-Simple-Web-Server-in-Java-HTTP-Server
That being shared, this is quite primitive, I'd recommend using any third party library or light-weight Java server like Grizzly or Jetty if not a server like Apache Tomcat utilizing J2EE Servlets which are made for this purpose.

Multiple HTTP request happening with single call on frequent network change in android

I am making a HTTP URLconnection for my JSON upload in android. The request is an Intent Service. I have a broadcast receiver which checks for Network change and calls the Intent Service to make the upload.
But in doing so when a user is frequently changing the network for Wifi to cellular or Vic-verse at times the same JSON is uploaded more than once.
BroadcastReciver.java
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equalsIgnoreCase(intent.getAction())) {
if (Utils.hasActiveInternet(context)) {
TripManager.uploadUnSubmittedTripsAsync(context, DataStore.getApplicationPath(context));
Logger.log("OSBroadcastReceiver","onReceive",new String[]{"Network available"});
}else
Logger.log("OSBroadcastReceiver","onReceive",new String[]{"Network unavailable"});
}
}
Upload.java
private ServiceResponse executeServiceRequestInternal() {
ServiceResponse serviceResponse = null;
HttpURLConnection connection = null;
boolean delay = false;
if (!Utils.hasActiveInternet(mContext)) {
pushError("error");
} else {
try {
if (jsonFile.exists()) {
do {
connection = (HttpURLConnection) getServiceUrl(mRequest.serviceUrl).openConnection();
setHttpRequestType(mRequest, connection);
setContentType(mRequest, connection);
setHeaders(mRequest, connection);
connection.setUseCaches(false);
connection.setDoInput(true);
if (mRequest.requestType != GET_REQUEST) {
connection.setDoOutput(true);
}
connection.setConnectTimeout(mRequest.requestTimeout);
connection.setReadTimeout(mRequest.requestTimeout);
connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Keep-Alive", "off");
if (mRequest.requestData != null && mRequest.requestData.length() > 0) {
sendRequestWithData(connection);
}
connection.connect();
int responseCode = connection.getResponseCode();
if (delay) {
Thread.sleep(TIME_BEFORE_RETRY);
}
if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_ACCEPTED && responseCode != HttpURLConnection.HTTP_CREATED) {
String serverResponse = connection.getResponseMessage();
if (null == serverResponse) serverResponse = serverError;
serviceResponse = getServiceResponse(responseCode,
serverResponse);
pushServerError(responseCode, serverResponse);
} else {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
String resultString = response.toString();
is.close();
if (TextUtils.isEmpty(resultString)) {
serviceResponse = getServiceResponse(
HttpURLConnection.HTTP_NO_CONTENT, "");
deleteTrip();
} else {
serviceResponse = getServiceResponse(
HttpURLConnection.HTTP_OK, resultString);
deleteTrip();
}
break;
}
// we did not succeed with connection (or we would have returned the connection).
connection.disconnect();
// retry
mRetryCounter++;
delay = true;
} while (mRetryCounter < MAX_RETRY_COUNT);
} else {
if (connection != null) {
connection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
return serviceResponse;
}
Thank in advance.
I had the same issue and after adding connection.setChunkedStreamingMode(0) it was solved; this is the snippet you can refer,
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.setUseCaches(false);
request.setDoOutput(true);
request.setDoInput(true);
request.setConnectTimeout(CONNECTION_TIMEOUT);
request.setRequestMethod(HTTP_POST);
request.setReadTimeout(CONNECTION_TIMEOUT);
request.setChunkedStreamingMode(0);
DataOutputStream printout = new DataOutputStream(request.getOutputStream());
NameValuePair dataToSend = new NameValuePair(AppEnvironment.DATA, data);
// printout.write(getQuery(dataToSend));
printout.writeBytes(getQuery(dataToSend));
printout.flush();
printout.close();
private String getQuery(NameValuePair params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
result.append(URLEncoder.encode(params.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(params.getValue(), "UTF-8"));
// }
return result.toString();
}

Android : Sending image as byte[] by Http Get or Post Request

I need to upload image to the web server and it require the ImageContent to be in byte[] at the documentation it said base64Binary but i tried base64 encoded string and no use
that is my class :
private class background extends AsyncTask<byte[],Void,String> {
String url = "http://www.sample.com/_mobfiles/CLS_Account.asmx/UploadImage";
String charset = "UTF-8";
String param1 = "jpg";
#Override
protected String doInBackground(byte[]... params) {
try {
String query = String.format("ImageContent=%s&imageExtenstion=%s", params[0], URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
}
else {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = response.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] arr = buffer.toByteArray();
String decoded = new String(arr, "UTF-8");
System.out.println(decoded);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
that return (java.io.FileNotFoundException)
and the Base64 Encoded return (java.net.ProtocolException: Unexpected status line: Object moved)
Here is the Doc :
HTTP GET
The following is a sample HTTP GET request and response. The placeholders shown need to be replaced with actual values.
GET /_mobfiles/CLS_Account.asmx/UploadImage?ImageContent=base64Binary&imageExtenstion=string HTTP/1.1
Host: www.sample.com
and the response is like
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
HTTP POST
The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.
POST /_mobfiles/CLS_Account.asmx/UploadImage HTTP/1.1
Host: www.sample.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
ImageContent=base64Binary&imageExtenstion=string
and the response is like
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
Can you try this in your chrome console and tell the output.
xmlhttp=new XMLHttpRequest();
var url = '/_mobfiles/CLS_Account.asmx/UploadImage?';
var base64 ='R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='
xmlhttp.open("GET",url + 'ImageContent='+base64+'&imageExtenstion=gif',true);
xmlhttp.send();
console.log(xmlhttp.response)
Try this too. If this also fails you gotta check the server. Atleast provide server method responsible for handling this.
xmlhttp=new XMLHttpRequest();
var url = '/_mobfiles/CLS_Account.asmx/UploadImage?';
var base64 ='R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='
xmlhttp.open("POST",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('ImageContent="'+base64+'"&imageExtenstion="gif"');
console.log(xmlhttp)
Use a Get request and use
var base64 ='R0lGODlhDwAPAKECAAAAzMzM%2F%2F%2F%2F%2FwAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH%2BH09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw%3D%3D'
I am sure this should work. I am really sorry My bad I should haven't made such a stupid mistake/
I haven't found a way but to send the whole SOAP envelope
So from a background thread AsyncTask i called callSOAPWebService(String data) when executed
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap resizedBitmap = Bitmap.createScaledBitmap(thumbnail, 150, 150, false);
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100,stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
new ImageUpload().execute(encoded);
from the UI thread
and on background
#Override
protected String doInBackground(String... params) {
callSOAPWebService(params[0]);
return null;
}
and the callSOAPWebService is as follow
private boolean callSOAPWebService(String data) {
OutputStream out = null;
int respCode;
boolean isSuccess = false;
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(GetData.NonOpDomain);
httpURLConnection = (HttpURLConnection) url.openConnection();
do {
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("Content-Type", "text/xml");
httpURLConnection.setRequestProperty("SendChunked", "True");
httpURLConnection.setRequestProperty("UseCookieContainer", "True");
HttpURLConnection.setFollowRedirects(false);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(true);
httpURLConnection.setRequestProperty("Content-length", getReqData(data).length + "");
httpURLConnection.setReadTimeout(100 * 1000);
// httpURLConnection.setConnectTimeout(10 * 1000);
httpURLConnection.connect();
out = httpURLConnection.getOutputStream();
if (out != null) {
out.write(getReqData(data));
out.flush();
}
respCode = httpURLConnection.getResponseCode();
Log.e("respCode", ":" + respCode);
} while (respCode == -1);
// If it works fine
if (respCode == 200) {
try {
InputStream responce = httpURLConnection.getInputStream();
String str = convertStreamToString(responce);
System.out.println(".....data....." + str);
InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"));
XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(is, null);
parseXMLAndStoreIt(myparser);
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
isSuccess = false;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out = null;
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
return isSuccess;
}
and the helper method
public volatile boolean parsingComplete = true;
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text = null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("UploadImageResult")) {
uploadedImage = text;
uploadedImage = uploadedImage.replace("\"", "");
}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public static String createSoapHeader() {
String soapHeader;
soapHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + ">";
return soapHeader;
}
public static byte[] getReqData(String data) {
StringBuilder requestData = new StringBuilder();
requestData.append(createSoapHeader());
requestData.append("<soap:Body>" + "<UploadImage" + " xmlns=\"http://example.org/\">" + "<ImageContent>").append(data).append("</ImageContent>\n").append("<imageExtenstion>jpg</imageExtenstion>").append("</UploadImage> </soap:Body> </soap:Envelope>");
Log.d("reqData: ", requestData.toString());
return requestData.toString().trim().getBytes();
}
private static String convertStreamToString(InputStream is)
throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Hope it will help some one in the future

Categories