App crashes on SocketTimeoutException in Android - android

I have implemented AsyncTask in Activity properly (based on many sources).
Also I have investigated SocketTimeoutException and catche exception as you can see in the code below.
Anyway when I stop webapi and simulate SocketTimeoutException the app crashes immediately. (Please, check the error's message.)
Debuging code goes to IOException and then I see the error's message and app restarts.
Code
private class FetchHauls extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
AppSettings.ComplexPreferences complexPreferences = AppSettings.ComplexPreferences.getComplexPreferences(context, "App_Settings", 0);
AppSettings appSettings = complexPreferences.getObject("App_Settings", AppSettings.class);
if (appSettings != null) {
String uri = appSettings.getIpAddress() + "/api/Version1/GetGrandTotalStats";
GrandTotalStatsRequest grandTotalStatsRequest = new GrandTotalStatsRequest();
Date d = new Date();
CharSequence timeOfRequest = DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
grandTotalStatsRequest.AtTime = timeOfRequest.toString();
grandTotalStatsRequest.DeviceID = appSettings.getDeviceID();
grandTotalStatsRequest.DeviceSerialNumber = appSettings.getSerialNumber();
Gson gson = new Gson();
String json = gson.toJson(grandTotalStatsRequest);
//Connect
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(60000);
urlConnection.setReadTimeout(55000);
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(json);
writer.close();
outputStream.close();
String result = null;
//Read
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String l = null;
StringBuilder sb = new StringBuilder();
while ((l = bufferedReader.readLine()) != null) {
sb.append(l);
}
bufferedReader.close();
result = sb.toString();
}
return result;
}
} catch (IOException e) {
} catch (Exception e) {
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException ex) {
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (isCancelled()) {
return;
}
swiperefresh.setRefreshing(false);
taskFetchHauls = null;
if (TextUtils.isEmpty(s)) return;
try {
// Some code...
} catch (Exception ex) {
Log.e(PAGE_TITLE, ex.getMessage());
}
}
}
}
Error
java.net.SocketTimeoutException: failed to connect to /172.15.15.2 (port 1067) after 60000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:169)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
at java.net.Socket.connect(Socket.java:884)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160)
at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:67)
at com.android.okhttp.Connection.connect(Connection.java:152)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at android.apps.ktk.company.gpsmegatracker.Activities.GrandStatActivity$FetchHauls.doInBackground(GrandStatActivity.java:291)
at android.apps.ktk.company.gpsmegatracker.Activities.GrandStatActivity$FetchHauls.doInBackground(GrandStatActivity.java:259)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Disconnected from the target VM, address: 'localhost:8617', transport: 'socket'

If you want to catch a SocketTimeoutException, then you should use the following pattern. Note carefully that we catch exceptions from most specific to most general. Because SocketTimeoutException is a child of IOException, we catch the former first. Using the reverse order will result in the error you were seeing. Finally, we catch general Exception last.
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
// make the async call
}
catch (SocketTimeoutException se) {
// display timeout alert to user
}
catch (IOException e) {
// handle general IO error
}
catch (Exception e) {
// just in case you missed anything else
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException ex) {
}
}
}
}

Related

Android 6.0 HtppURLConnection Crash Error

I'm using this codes in asynctask for load data from URL. I added internet permissions in manifest.xml, I haven't any errors on Android Studio but when i debugging application, going crash. Where is my fault?
protected Void doInBackground(Void... params) {
try {
URL url = new URL("my_url");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
jsonString = buffer.toString();
if(connection != null) { connection.disconnect(); }
try {
if(reader != null) { reader.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Thanks..

doInBackground throws NullPointerException for no reason

In here the code with BufferedReaderand line = reader.readLine() works
public class WeatherService extends AsyncTask<TaskParams, Void, String> {
private WeatherServiceCallback callback;
private Exception exception;
public WeatherService(WeatherServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?lat=" +
params[0].getLat() + "&lon=" + params[0].getLon() +
"&units=" + TaskParams.getUnits() +
"&type=" + TaskParams.getAccuracy() + "&lang=" + TaskParams.getLanguage() +
"&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.serviceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
Parameters parameters = new Parameters();
parameters.poopulate(data);
callback.serviceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I copy-pasted code to other class since it has very similar functionality and now for no reason I'm getting NullPointerException in while ((line = reader.readLine()) != null) and I have no idea why since as I said it's copy-pasted (I only changed URL and object returned if serivce succeeds)
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
private URLConnection connection;
private InputStream inputStream;
private InputStreamReader streamReader;
private BufferedReader reader;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
try
{
connection = url.openConnection();
}
catch (IOException e)
{
exception = new Exception("Connection error");
}
try
{
inputStream = connection.getInputStream();
}
catch (IOException e)
{
exception = new Exception("Input stream error");
}
try
{
streamReader = new InputStreamReader(inputStream);
}
catch (NullPointerException e)
{
exception = new Exception("Input stream reader error");
}
try
{
reader = new BufferedReader(streamReader);
}
catch (NullPointerException e)
{
exception = new Exception("Buffered reader error");
}
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any clue?
EDIT
This is rewritten code for PollutionActivity. Callback function serviceFailure prints now the URL address on my phone's screen
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
catch (IOException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Debugging showed me that code jumps to exception after
InputStream inputStream = connection.getInputStream();
If you are getting NPE for reader then it means that reader is not getting initialized and going null.Your code is getting crash at line 23 and 89. So I believe that the problem is right at the start somewhere and not at the point itself, may be some object is going null like connection.Since line number is not displayed here.Check null pointer for every object like if (connection!=null). Since the initial data is coming null,maybe input stream or some other data,hence your reader object is not getting initialized.Also check if you are getting value for every object in debug.

Connect Local Web servcies from android phone

I am trying to connect to web services running on my machine(localhost). I have tested from restClient and its working fine. But, I am unable to test them from android application(which I am working on). There seems to be a connection problem.
This is the calling code:
#Override
protected Void doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String mobileNo = params[0];
String format = "json";
try {
// Construct the URL for Login
JSONObject requestObject = new JSONObject();
requestObject.put(MOBILE_NO, mobileNo);
final String LOGIN_BASE_URL =
"http://192.168.42.251:8080/SpringSample/login";
Uri builtUri = Uri.parse(LOGIN_BASE_URL).buildUpon()
.build();
URL url = new URL(builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// Request Body
OutputStream outStream = urlConnection.getOutputStream();
if (outStream == null) {
throw new ConnectException();
}
outStream.write(requestObject.toString().getBytes());
int responseCode = urlConnection.getResponseCode();
if (responseCode == 409) {
} else if (responseCode == 201) {
} else {
throw new ConnectException();
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
} catch (JSONException e) {
Log.e(LOG_TAG, "Error ", e);
} catch (ConnectException e) {
Log.e(LOG_TAG, "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
Exception is :
Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)

SocketTimeoutException in HttpURLConnection randomly in getResponseCode

I am getting following error in con.getResponseCode()
java.net.SocketTimeoutException: failed to connect to example.com (port 80) after 3000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:223)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:475)
at java.net.Socket.connect(Socket.java:861)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:152)
at com.android.okhttp.Connection.connect(Connection.java:101)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)
First time when it gets called it works perfectly.
But it stops working after it and it may start working randomly after some time.
public class HTTPLoader {
public static String loadContentFromURLGET(String urlString,List<String[]> getVars,Context context){
int retry = 0;
HttpURLConnection con=null;
BufferedReader in = null;
StringBuffer response=null;
if (!isConnectingToInternet(context)){
return "{'error':'No Internet connection!'}";
}
while (retry++<=RETRY_CNT) {
try {
String urlParameters = "";
for (String[] var : getVars) {
urlParameters += var[0] + "=" + URLEncoder.encode(var[1], "UTF-8") + "&";
}
if (urlParameters.length() > 1) {
urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
}
if (urlString.charAt(urlString.length() - 1) != '?') {
urlString += "&";
}
URL url = new URL(urlString + urlParameters);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(3000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoInput(true);
con.setDoOutput(true);
int responseCode = con.getResponseCode();
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
retry = RETRY_CNT+1;
break;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}finally {
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con!=null) {
con.disconnect();
}
in = null;
con = null;
}
}
if (response!=null)
return new String(response);
return "{'error':'No Internet connection!'}";
}
}
This loadContentFromURLGET is getting called from IntentService
public class ChatUtil extends IntentService{
protected String loadAllChats(String date){
String response = "";
try {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String email = sharedPreferences.getString(QuickstartPreferences.EMAIL, "");
List<String[]> postVars = new ArrayList<>();
postVars.add(new String[]{"getconversation", "yes"});
postVars.add(new String[]{"user_id", email});
postVars.add(new String[]{"last_date", date});
String urlString = getString(R.string.get_conversation_url);
response = HTTPLoader.loadContentFromURLGET(urlString, postVars,getApplicationContext());
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("error")) {
//Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
return jsonObject.getString("error");
}
}catch (JSONException e) {
}
}
protected void onHandleIntent(Intent intent) {
String task = intent.getStringExtra(QuickstartPreferences.CURRENT_TASK);
Intent nintent;
String date = "";
String[] arr3 = new NewsDBUtil(getApplicationContext()).getLastChatEntry(null);
if (arr3!=null)
date = arr3[1];
loadAllChats(date);
nintent = new Intent(QuickstartPreferences.LOADING_ALL_CHAT);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(nintent);
}
}
Tried closing and disconnecting stream in finally block.
But no Success.
you can put con.getResponseCode(); between try ...catch block if it throw SocketTimeoutException Exception make another try , but make sure you extend your timeout
if (responseCode != 200) {
....
...
} catch (final java.net.SocketTimeoutException e) {
// connection timed out...let's try again
}
may this help
Without specific ContentLength via setFixedLengthStreamingMode
I found some devices generated incomplete http request
cause the server has to wait until either server or client timed out
you can use wireshark to analyze the problem

Android HttpUrlConnection fails with 400 response after a few hundred success responses

I'm using HttpUrlConnection in my android app. I'm trying to send a post request to a particular url every 2 seconds. Below is the code for the same.
The issue I have is, I get 200 OK response for the first approx 200-250 calls, and after that every call starts failing with 400 Bad requestYour browser sent an invalid request.
I force stop my app, and then as mentioned above the first 200-250 hits to my url comes with 200 OK and then starts failing with 400. I was able to reproduce this consistently every time. I tried almost like 10 times and the same thing happens.
When I tried AndroidHttpClient I was able to make close to like 15000 hits to the same url without a single failure, so definitely not a server issue.
I'm trying to understand what is the issue with httpUrlConnection, as I would like to stick with httpUrlConnection as it is recommended by Google. As far as I see I have done all error handling fine.
I even tried to set http.keepAlive System property to false at the start of my appln/ included connection "Close" header before making the connection but nothing helped.
Could someone help me understand what am I doing wrong here?
HttpURLConnection con = null;
final BufferedReader rd = null;
final BufferedOutputStream wr = null;
final InputStreamReader isr = null;
ServerConnectionData serverConnectionData = null;
try {
serverConnectionData = (ServerConnectionData) connectionData;
final String urlPath = serverConnectionData.getUrlPath();
final URL url = new URL(urlPath);
trust();
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
final URLConnection urlConnection = url.openConnection();
con = (HttpURLConnection) urlConnection;
con.setRequestMethod("POST");
// con.addRequestProperty("Connection", "Keep-Alive");
// con.addRequestProperty("Connection", "Close");
if (serverConnectionData.getJsonData() != null) {
con.addRequestProperty(
"Content-Length",
Integer.toString(serverConnectionData.getJsonData().getBytes(
Charset.forName("UTF8")).length));
}
if (serverConnectionData.getAdditionalHeaders() != null) {
final Map<String, String> additionalHeaders =
serverConnectionData.getAdditionalHeaders();
final Set<String> keySet = additionalHeaders.keySet();
for (final Object key : keySet) {
con.addRequestProperty((String) key, additionalHeaders.get(key));
}
}
final String authToken = "Bearer " + "my outh token";
con.addRequestProperty("Authorization", authToken);
con.addRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setUseCaches(false);
con.setConnectTimeout(60000);
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
sendData(con, serverConnectionData);
responseCode = con.getResponseCode();
responseText = getResponseText(con);
if (responseCode == 200) {
// success
} else {
// failure }
}
} catch (final MalformedURLException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} catch (final IOException e) {
Log.e(e.toString());
try {
if (null != con) {
responseCode = con.getResponseCode();
responseText = getResponseText(con);
}
if (responseCode == 401) {
// handle 401 response
} else {
final ConnectionException ce =
new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
ce.setResponseCode(responseCode);
throw ce;
}
} catch (final UnsupportedEncodingException uee) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
uee.getStackTrace());
} catch (final IOException ioe) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
ioe.getStackTrace());
}
} catch (final KeyManagementException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} catch (final NoSuchAlgorithmException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} catch (final Exception e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} finally {
if (wr != null) {
try {
wr.flush();
wr.close();
} catch (final IOException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
if (isr != null) {
try {
isr.close();
} catch (final IOException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
if (rd != null) {
try {
rd.close();
} catch (final IOException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
if (con != null) {
con.disconnect();
}
}
private void trust() throws NoSuchAlgorithmException, KeyManagementException {
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkClientTrusted(final java.security.cert.X509Certificate[] certs,
final String authType) {
}
#Override
public void checkServerTrusted(final java.security.cert.X509Certificate[] certs,
final String authType) {
}
}
};
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
public void sendData(final HttpURLConnection con, final ServerConnectionData serverConnectionData)
throws IOException, ConnectionException {
final String requestJSON = serverConnectionData.getJsonData();
if (requestJSON != null) {
BufferedOutputStream bufferedOutputStream = null;
try {
bufferedOutputStream = new BufferedOutputStream(con.getOutputStream());
bufferedOutputStream.write(requestJSON.getBytes());
bufferedOutputStream.flush();
} finally {
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (final IOException e) {
setOnlineStatus(ONLINE_STATUS_BAD);
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
}
}
}
public String getResponseText(final HttpURLConnection con) throws IOException {
InputStream stream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
String responseText = null;
try {
final int responseCode = con.getResponseCode();
if (200 == responseCode) {
stream = con.getInputStream();
}
if (null == stream) {
stream = con.getErrorStream();
}
if (null == stream) {
return "";
}
inputStreamReader = new InputStreamReader(stream, "UTF8");
bufferedReader = new BufferedReader(inputStreamReader);
final StringBuilder sb = new StringBuilder("");
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
responseText = sb.toString();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (stream != null) {
stream.close();
}
}
return responseText;
}

Categories

Resources