httpurlconnection.getoutputstream() takes 2 minutes - android

Here is my code:
public class HttpClient {
public String AddressBase = "";
String _AccessToken = "";
String _AccessToken = "";
public HttpClient() {
}
public HttpClient(String accessToken) {
_AccessToken = accessToken;
}
private HttpURLConnection _CreateConnection(String url, final ArrayList<Pair<String, String>> params) throws IOException {
Uri.Builder uriB1 = Uri.parse(AddressBase).buildUpon()
.appendEncodedPath(url);
if (params != null)
for (Pair<String, String> p :
params) {
uriB1 = uriB1.appendQueryParameter(p.first, p.second);
}
URL callUrl = new URL(uriB1.build().toString());
HttpURLConnection connection = (HttpURLConnection) callUrl.openConnection();
if (!_AccessToken.isEmpty())
connection.setRequestProperty("Authorization", "Bearer " + _AccessToken);
return connection;
}
private <T, Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final T object, final Class<Y> objectClass) {
Log.e("check net", "_post");
return _Post(url, params, AppConstants.Gson_Get().toJson(object), "application/json", objectClass);
}
private <Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final String postBodyContent, String postBodyContentType, final Class<Y> objectClass) {
Y r = null;
HttpURLConnection connection = null;
try {
Log.e("tag", " try create connection");
connection = _CreateConnection(url, params);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-type", postBodyContentType);
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
if (postBodyContent != null && !postBodyContent.isEmpty()) {
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
wr.write(postBodyContent);
wr.flush();
}
connection.connect();
Log.e("tag", " connection connected");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
String h1 = connection.getHeaderField("Content-Encoding");
if (h1 != null && h1.equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
private String _ConvertStreamToString(InputStream inputStream) {
Log.e("checknet", "cnovert stram to string");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return stringBuilder.toString();
}
public <T, Y> Y Post(final String url, final T object, final Class<Y> objectClass) {
return _Post(url, null, object, objectClass);
}
public <T> T PostParamsInQuery(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
return _Post(url, params, null, "application/json", objectClass);
}
public <T> T PostParamsInBody(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
StringBuilder postBodyContent = new StringBuilder("");
for (Pair<String, String> p :
params) {
try {
if (postBodyContent.length() != 0)
postBodyContent.append('&');
postBodyContent.append(URLEncoder.encode(p.first, "UTF-8"));
postBodyContent.append("=");
postBodyContent.append(URLEncoder.encode(p.second, "UTF-8"));
} catch (Exception e) {
}
}
return _Post(url, null, postBodyContent.toString(), "application/x-www-form-urlencoded", objectClass);
}
public <T> T Get(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
T r = null;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
if (connection.getHeaderField("Content-Encoding").equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public boolean Delete(String url, final ArrayList<Pair<String, String>> params) {
boolean r = false;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.connect();
r = connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT;
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public <T, Y> Y InvokeApi(String apiName, final T arg, Class<Y> returnClass) {
return Post(String.format("/api/%s", apiName), arg, returnClass);
}
public <T, Y> void InvokeApiAsync(final String apiName, final T arg, final Class<Y> returnClass, final ActionListener<Y> listener) {
new AsyncTask<Void, Void, Y>() {
#Override
protected Y doInBackground(Void... params) {
return InvokeApi(apiName, arg, returnClass);
}
#Override
protected void onPostExecute(Y result) {
if (listener != null) {
listener.Action(result);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
When I call InvokeApiAsync it takes long time about 3 minutes to get response because of .getoutputstream(). I've been using AsyncTask for parallel connection too.I dont know what to do anymore I will be grateful for any help.

I had this problem before, check your network (perhaps WiFi) proxy on your device that you test your code on!
Android tries to connect to the proxy and if it fails (incorrect proxy or very slow one) it will wait for a long time (default) to get the outputStream.
Either turn the proxy off or set the time out to smaller value to get the timeout exception sooner!

You had better use an IntentService instead of AsyncTask for API connections.

Related

android get url from edit text and use it in rest api to upload data

Here is my android rest request code but the where i get the url from edit text using its id but "getString" gets flagged(can't be resolved). Please help
class RESTRequest
{
//final String ADD_STROKE_URL = "";
final String ADD_STROKE_URL = new String[]{ getString(R.id.buttonUploadURL)};
public Boolean success = null;
private JSONObject params;
private String strokeId;
private HashSet<Point> localPoints;
private StrokeManagerCallback callback;
public static String encode(Object x) {
try {
return URLEncoder.encode(String.valueOf(x),"UTF-8");
} catch (UnsupportedEncodingException e) {
return(String.valueOf(x));
}
}
public RESTRequest(JSONObject params,String strokeId,Set<Point> points,StrokeManagerCallback callback)
{
this.params = params;
this.strokeId = strokeId;
this.localPoints = new HashSet<Point>();
this.localPoints.addAll(points);
this.callback = callback;
new ExecuteREST().execute();
}
private class ExecuteREST extends AsyncTask<Void, Void, String>
{
protected String doInBackground(Void ...arg0)
{
/* Build URL query */
StringBuffer local = new StringBuffer(ADD_STROKE_URL);
if(params != null)
{
local.append("?");
Iterator<?> k = params.keys();
while(k.hasNext()){
try {
String key = (String) k.next();
Object value = params.get(key);
local.append(encode(key));
local.append("=");
local.append(encode(value));
if(k.hasNext()){
local.append("&");
}
}
catch (JSONException e) {e.printStackTrace();}
}
}
HttpURLConnection urlConn = null;
StringBuffer response = new StringBuffer("error");
try
{
URL url = new URL(local.toString());
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
//Get Response
InputStream is = urlConn.getInputStream();
BufferedReader rd = new BufferedReader(newInputStreamReader(is));
String line;
response = new StringBuffer();
try{
while((line = rd.readLine()) != null) {
response.append(line);
}
}
finally{
if(urlConn != null){
urlConn.disconnect();
urlConn = null;
}
if(rd != null){
rd.close();
rd = null;
}
}
if(callback != null){
callback.onSuccess(strokeId, localPoints);
}
} catch (ConnectException e) {
callback.onFailure(strokeId, localPoints);
} catch (UnknownHostException e) {
callback.onFailure(strokeId, localPoints);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (EOFException e) {
response = new StringBuffer("No response from server");
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
finally{
if(urlConn != null){
urlConn.disconnect();
}
}
return response.toString();
}
}
you can get String Resources like this
Resources res = context.getResources();
final String ADD_STROKE_URL = new String[]{ res.getString(R.id.buttonUploadURL)};
and now you can pass that url in AcycncTask class like this
public RESTRequest(JSONObject params,String
strokeId,Set<Point>points,StrokeManagerCallback callback){
this.params = params;
this.strokeId = strokeId;
this.localPoints = new HashSet<Point>();
this.localPoints.addAll(points);
this.callback = callback;
new ExecuteREST(/*Pass url here that you will get in doInBackground method */)
.execute();
}
private class ExecuteREST extends AsyncTask<String, Void, String>{
protected String doInBackground(String ...arg0){
//get your url in arg0 variable
StringBuffer local = new StringBuffer(arg0[0]);
.
.
.
//Rest of yours ...

Android - HttpsURLConnection - BAD REQUEST

I am trying to send a POST request using Plivo (VoIP server) to send a SMS to my cell phone, but I just receive BAD REQUEST (Request Code 400).
The error I received is "error": "invalid json data sent in raw POST"
I can't find where it's wrong.
Can someone help me?
final AsyncTask<String, Void, Boolean> request = new AsyncTask<String, Void, Boolean>() {
#Override
protected Boolean doInBackground(String... strings) {
Boolean retorno = true;
HttpsURLConnection request = null;
try {
request = (HttpsURLConnection) finalUrl.openConnection();
System.out.println("Define POST");
request.setRequestMethod("POST");
request.setUseCaches(false);
request.setDoOutput(true);
System.out.println("Define propriedades");
request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Accept", "application/json");
request.setRequestProperty("Accept-Charset", "UTF-8");
request.setRequestProperty("charset", "UTF-8");
System.out.println("Define autenticação");
String autenticacao = authID + ":" + authToken;
String basic = "Basic " + new String(Base64.encode(autenticacao.getBytes(), Base64.NO_WRAP));
request.setRequestProperty("Authorization", basic);
System.out.println("Define parâmetros");
JSONObject params = new JSONObject();
params.put("dst", numeroDestino);
params.put("src", numeroOrigem);
params.put("text", body);
System.out.println("Faz conexão e requisição");
request.connect();
OutputStreamWriter postParaEnvio = new OutputStreamWriter(request.getOutputStream());
postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8"));
postParaEnvio.flush();
postParaEnvio.close();
int codigoStatus = request.getResponseCode();
for (Map.Entry<String, List<String>> header : request.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
if (codigoStatus == 202) {
System.out.println("OK");
} else {
System.out.println("Falha");
System.out.println(codigoStatus);
retorno = false;
}
} catch (IOException e) {
System.out.println("Falha Exception");
e.printStackTrace();
retorno = false;
} catch (JSONException e) {
e.printStackTrace();
retorno = false;
} finally {
request.disconnect();
}
return retorno;
}
#Override
protected void onPostExecute(Boolean result) {
indicadorDeAtividade.dismiss();
if(result) {
} else {
mostrarErro(0, R.string.erroEnviarCodigo);
}
}
}.execute();
SOLVED
When sending Json object, it must be passed to String but it cannot be coded.
Modifing the line postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8")); to postParaEnvio.write(params.toString()); solved the problem.
I Think this may help you.
By the way,
My Dependencies : gradle->
compile 'com.android.support:appcompat-v7:23.4.0'
class BackGround extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
String name = params[0];
String password = params[1];
String email = params[2];
String phone=params[3];
String data="";
int tmp;
try {
URL url = new URL("http://domain.com/yourFile.php");
String urlParams = "name="+name+"&password="+password+"&email="+email+"&phone="+phone;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("")){
s="Data Saved! Success...";
}
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
}
}

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.

Can Java's FutureTask be an alternative to AsyncTask?

The docs say AsyncTask is designed to handle short operations(few seconds maximum) and states that Java classes like FutureTask are better for operations that last long. So I tried to send my location updates to the server using FutureTask but I am getting NetworkOnMainThreadException. I don't want to use AsyncTask because I wanted to keep the http connection open until the updates are cancelled. Here is my code:
SendLocation updates = new SendLocation(idt, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
FutureTask ft = new FutureTask<String>(updates);
boolean b = ft.cancel(false);
ft.run();
class SendLocation implements Callable<String> {
String t, la, lo;
public SendLocation(String a, String b, String c){
this.t = a;
this.la = b;
this.lo = c;
}
public String call() {
sendUpdates(token, la, lo);
return "Task Done";
}
public void sendUpdates(String a, String b, String c){
HttpURLConnection urlConn = null;
try {
try {
URL url;
//HttpURLConnection urlConn;
url = new URL(remote + "driver.php");
urlConn = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", "true");
//urlConn.setDoInput(true); //this is for get request
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
try {
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("drt", a);
json.put("drlat", b);
json.put("drlon", c);
String postData = json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.flush();
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg = "";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line;
}
Log.i("msg=", "" + msg);
} catch (JSONException jsonex) {
jsonex.printStackTrace();
Log.e("jsnExce", jsonex.toString());
}
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex) {
ioex.printStackTrace();
try { //if there is IOException clean the connection and clear it for reuse(works if the stream is not too long)
int respCode = urlConn.getResponseCode();
InputStream es = urlConn.getErrorStream();
byte[] buffer = null;
int ret = 0;
// read the response body
while ((ret = es.read(buffer)) > 0) {
Log.e("streamingError", String.valueOf(respCode) + String.valueOf(ret));
}
// close the errorstream
es.close();
} catch(IOException ex) {
// deal with the exception
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code " + String.valueOf(e));
}
}
}
Doesn't it get executed in a worker thread? If the answer is no why does the docs say that it is an alternative to AsyncTask?
Your code must not be in the void run() method. This is where the asynchronous code is ran.

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