Getting the Response code 401 message in twitter api request - android

The below code is getting response code 401.please help anyone to get search tweets from twitter api.I am using http urlconnection instead of httprequest.I need to get response tweets using jsonobject
HttpURLConnection urlConnection=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitterlayout);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
twitter_consumer_key= "";
twitter_consumer_secret="";
oauth_token = "";
oauth_token_secret = "";
q="India";
String get_or_post = "GET";
// This is the signature method used for all Twitter API calls
String oauth_signature_method = "HMAC-SHA1";
// generate any fairly random alphanumeric string as the "nonce". Nonce = Number used ONCE.
String uuid_string = UUID.randomUUID().toString();
uuid_string = uuid_string.replaceAll("-", "");
String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here
// get the timestamp
Calendar tempcal = Calendar.getInstance();
long ts = tempcal.getTimeInMillis();// get current time in milliseconds
String oauth_timestamp = (new Long(ts/1000)).toString(); // then divide by 1000 to get seconds
// assemble the proper parameter string, which must be in alphabetical order, using your consumer key
String parameter_string = "lang=en&oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method +
"&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + URLEncoder.encode(oauth_token) + "&oauth_version=1.0&q=" + URLEncoder.encode(q) + "&result_type=mixed";`enter code here`
enter code here
Log.d("parameter_string=",parameter_string);
twitter_endpoint = "https://api.twitter.com/1.1/users/search.json";
twitter_url="https://api.twitter.com/1.1/users/search.json?q=india";
String signature_base_string = get_or_post + "&"+ URLEncoder.encode(twitter_endpoint) + "&" + URLEncoder.encode(parameter_string);
String oauth_signature = "";
try {
oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
}
catch (GeneralSecurityException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp +
"\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + URLEncoder.encode(oauth_signature) + "\",oauth_token=\"" + URLEncoder.encode(oauth_token) + "\"";
Log.d("Header String",authorization_header_string);
URL url = null;
try
{
Log.d("Url",twitter_url);
url = new URL(twitter_url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Host", "api.twitter.com");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setRequestProperty("Authorization",authorization_header_string);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setUseCaches(false);
int responseCode = urlConnection.getResponseCode();
Log.d("Response Code :", String.valueOf(responseCode));
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String responsedata = null;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(jsonCallbackToJson(builder.toString()));
Log.d("Toplevel", builder.toString());
}
catch (MalformedURLException e) {
e.printStackTrace();
Log.i("URL-ERROR:",e.toString());
}
catch (IOException | JSONException e)
{
e.printStackTrace();
Log.i("IO-ERROR:", e.toString());
}
}

401 means you have broke something with authentication
However, don't reinvent the wheel.
You can use TwitterCore Kit that handle authentication and is easy to use tool for your needs. It provides a TwitterApiClient for making authenticated Twitter API requests.

Related

Getting "(CSRF token missing or incorrect.)" in android

I am getting CSRF token mismatch error on Django server while running below piece of code.
Can some one help me identifying the issue here.
try{
loginUrl = new URL(urls[0]);
loginUrlConnection = (HttpURLConnection) loginUrl.openConnection();
loginUrlConnection.setRequestMethod("GET");
String userPass = "aniket" + ":" + "rinku123";
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);
loginUrlConnection.setRequestProperty("Authorization", basicAuth);
loginUrlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
loginUrlConnection.setRequestProperty("X-CSRF-TOKEN", "fetch");
loginUrlConnection.getContent();
if (HttpURLConnection.HTTP_OK == loginUrlConnection.getResponseCode()) {
cookie = loginUrlConnection.getHeaderField("Set-Cookie");
String[] parts = cookie.split("\\=|\\;"); // split response by " and find the string that's 64 characters (csrf token)
for(String s: parts) {
if(s.length() == 64) {
xcsrfToken = s;
break;
}
}
}
loginUrl = new URL(urls[0]);
loginUrlConnection = (HttpURLConnection) loginUrl.openConnection();
loginUrlConnection.setRequestMethod("POST");
userPass = "aniket" + ":" + "rinku123";
basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);
loginUrlConnection.setRequestProperty("Authorization", basicAuth);
loginUrlConnection.setRequestProperty("cookie", cookie);
loginUrlConnection.setRequestProperty("X-CSRF-TOKEN", xcsrfToken);
loginUrlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
loginUrlConnection.setConnectTimeout(10000);
loginUrlConnection.setDoInput(true);
loginUrlConnection.setDoOutput(true);
loginUrlConnection.setUseCaches(true);
loginUrlConnection.connect();
error :: Forbidden (CSRF token missing or incorrect.): /accounts/login/
Use from django.views.decorators.csrf import csrf_exempt On your view.
You can use it as decorator like this
#csrf_exempt
class Myview(View):
template_name = '1.html'

Apache HTTP Client Android Exception on Execute only for LG G3 6.0

I've taken over an android app that takes pictures and attaches them to jobs for a larger software system at a company's home base- it has worked fine until recently.
It seems that only on LG G3 phones that have upgraded to Android 6.0 there is an exception in this prodecure:
public static String frapiGetRequest(String transaction, ArrayList<Content> parameters) {
StringBuilder builder = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(HOST,PORT,SCHEME);
String url = SCHEME + "://" + HOST + "/" + transaction;
if (parameters != null && parameters.size() > 0) {
url += "?" + buildParameterString(parameters);
}
Utilities.bLog(TAG, "Making FrapiRequest -- " + url);
try {
HttpGet getRequest = new HttpGet(url);
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(USERNAME, PASSWORD));
/**Exception Occurs Here**/
HttpResponse response = client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = -1;
statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Utilities.bLog(TAG,"Frapi Request Succeeded");
}
else {
Utilities.bLog(TAG, "Frapi Request Failed: " + url);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Utilities.eLog(e);
} catch (IOException e) {
e.printStackTrace();
Utilities.eLog(e);
} catch (Exception e) {
e.printStackTrace();
Utilities.eLog(e);
}
return builder.toString();
}
The stack trace
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at org.apache.http.impl.auth.DigestScheme.isGbaScheme(DigestScheme.java:210)
at org.apache.http.impl.auth.DigestScheme.processChallenge(DigestScheme.java:176)
at org.apache.http.impl.client.DefaultRequestDirector.processChallenges(DefaultRequestDirector.java:1097)
at org.apache.http.impl.client.DefaultRequestDirector.handleResponse(DefaultRequestDirector.java:980)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:490)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at com.rossware.sd_quickpics.Utilities.frapiGetRequest(Utilities.java:111)
at com.rossware.sd_quickpics.Business.authenticate(Business.java:83)
at com.rossware.sd_quickpics.MainActivity$AuthenticateAsyncTask.doInBackground(MainActivity.java:320)
at com.rossware.sd_quickpics.MainActivity$AuthenticateAsyncTask.doInBackground(MainActivity.java:307)
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)
This hasn't been reported on any other phone.. I would use HttpURLConnection But it doesn't support Digest Authentication (which is currently what our frapi server is using)
I'm just not sure if there's any way to continue using the authentication mechanism we have or if I have to implement a different protocol in frapi (hopefully without breaking all of our existing applications..) or if there is another way to bypass this issue for the folks with these phones? This issue is pretty restricted (one client who has about 10 phones, not the end of the world, but definitely a major issue for them)
Is there anything in android that I can do to resolve this kind of problem for the affected users? Does it seem like the code is incorrect?
It is possible to use DigestAuth with HttpUrlConnection:
private InputStream connect(String urlStr, String username, String password) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) new URL(urlStr).openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
try {
return connection.getInputStream();
} catch(Exception e) {
if (connection.getResponseCode() == 401) {
String header = connection.getHeaderField("WWW-Authenticate");
String uri = new URL(urlStr).getFile();
String nonce = Tools.match(header, "nonce=\"([A-F0-9]+)\"");
String realm = match(header, "realm=\"(.*?)\"");
String qop = match(header, "qop=\"(.*?)\"");
String algorithm = match(header, "algorithm=(.*?),");
String cnonce = generateCNonce();
String ha1 = username + ":" + realm + ":" + password;
String ha1String = md5digestHex(ha1);
String ha2 = "GET" + ":" + uri;
String ha2String = md5digestHex(ha2);
int nc = 1;
String response = ha1String + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2String;
String responseString = md5digestHex(response);
String authorization =
"Digest username=\"" + username + "\"" +
", realm=\"" + realm + "\"" +
", nonce=\"" + nonce + "\"" +
", uri=\"" + uri + "\"" +
", qop=\"" + qop + "\"" +
", nc=\"" + nc + "\"" +
", cnonce=\"" + cnonce + "\"" +
", response=\"" + responseString + "\"" +
", algorithm=\"" + algorithm + "\"";
HttpURLConnection digestAuthConnection = prepareConnection(urlStr);
digestAuthConnection.setRequestMethod("GET");
digestAuthConnection.setRequestProperty("Authorization", authorization);
return processResponse(digestAuthConnection);
} else throw e;
}
}
public static String match(String s, String patternString, boolean strict) {
if (!isEmpty(s) && !isEmpty(patternString)) {
Pattern pattern = Pattern.compile(patternString);
if (pattern != null) {
Matcher matcher = pattern.matcher(s);
if (matcher != null && matcher.find() && (matcher.groupCount() == 1 || !strict)) {
return matcher.group(1);
}
}
}
return null;
}
public static String match(String s, String patternString) {
return match(s, patternString, true);
}
public static byte[] md5Digist(String s) {
try {
MessageDigest md5 = MessageDigest.getInstance("md5");
md5.update(s.getBytes());
return md5.digest();
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String digest2HexString(byte[] digest) {
String digestString="";
int low, hi;
for (int i = 0; i < digest.length; i++) {
low = (digest[i] & 0x0f ) ;
hi = ((digest[i] & 0xf0) >> 4);
digestString += Integer.toHexString(hi);
digestString += Integer.toHexString(low);
}
return digestString;
}
public static String md5digestHex(String s) {
return digest2HexString(md5Digist(s));
}
public static String generateCNonce() {
String s = "";
for (int i = 0; i < 8; i++) {
s += Integer.toHexString(new Random().nextInt(16));
}
return s;
}
I ran into a similar issue today and just started using HttpClient for Android
Added dependency compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1' to build.gradle.
Replace new DefaultHttpClient() with HttpClientBuilder.create().build()
There are probably some other minor refactors you might need to make in other portions of the code, but that should be pretty straight forward.

google direction gives 0 values

hey I have used google direction to get duration it's working but sometime it return 0 value to json array routs. when I tested a day after return a value. is there any limitation for google direction request per day ?
and here is my function to get duration
public String getDistanceInfo(LatLng origin, LatLng dest) {
StringBuilder stringBuilder = new StringBuilder();
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String dura = "";
try {
String sensor = "sensor=false";
String output = "json";
String mode = "mode=walking";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// Output format
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
//String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + str_origin + "," + str_dest + "&destination=" + destinationAddress + "&mode=driving&sensor=false";
HttpPost httppost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject duration = steps.getJSONObject("duration");
dura = duration.getString("text");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dura;
}
org.json.JSONException: Index 0 out of range [0..0)
org.json.JSONArray.get(JSONArray.java:282)
org.json.JSONArray.getJSONObject(JSONArray.java:510)
Check to see if you are also getting something like this too in your JSON response apart from 0 for the duration.
{"status":"OVER_QUERY_LIMIT","routes":[]}.
This means that you are exceeding the limits of the Direction API usage. Please note that for standard version there are only 2,500 free directions requests per day available. If you need to request more, their are additional charges associated.
Check the official documentation on Google Maps Directions API Usage Limits more details.

Android retrieve return value from WCF

I have an Android app that posts to a web service via the code below and it all works fine. But the myContract method in the service returns a Boolean, true or false. How do I retrieve that value so I can tell my app to move on or not if false?
HttpPost request = new HttpPost(SERVICE_URI + "/myContract/someString");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Edit
Sorry about the edit, but using HttpResponse, and then logging or toasting response.toString() returns a string I don’t understand!
Update
Thanks Shereef,
But that seems like a bit too much information and code to do what I was trying to do. I have added some code below that works but I’m not sure if it’s right. The service will return a Boolean true or false as to whether or not the POST was successful, but I seem to be retrieving it as a string!
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject jsonResponse = new JSONObject(new String(buffer));
String ServiceResponse = jsonResponse.getString("putCommuniqueResult");
Log.d("WebInvoke", "Saving : " + ServiceResponse);
Is this ok? It works but I’m not sure if its right!
Cheers,
Mike.
private static String getDataFromXML(final String text) {
final String temp = new String(text).split("<")[2].split(">")[1];
final String temp2 = temp.replace("<", "<").replace(">", ">")
.replace("&", "&");
return temp2;
}
/**
* Connects to the web service and returns the pure string returned, NOTE:
* if the generated url is more than 1024 it automatically delegates to
* connectPOST
*
* #param hostName
* : the host name ex: google.com or IP ex:
* 127.0.0.1
* #param webService
* : web service name ex: TestWS
* #param classOrEndPoint
* : file or end point ex: CTest
* #param method
* : method being called ex: TestMethod
* #param parameters
* : Array of {String Key, String Value} ex: { { "Username",
* "admin" }, { "Password", "313233" } }
* #return the trimmed String received from the web service
*
* #author Shereef Marzouk - http://shereef.net
*
*
*/
public static String connectGET(final String hostNameOrIP,
final String webService, final String classOrEndPoint,
final String method, final String[][] parameters) {
String url = "http://" + hostNameOrIP + "/" + webService + "/"
+ classOrEndPoint + "/" + method;
String params = "";
if (null != parameters) {
for (final String[] strings : parameters) {
if (strings.length == 2) {
if (params.length() != 0) {
params += "&";
}
params += strings[0] + "=" + strings[1];
} else {
Log.e(Standards.TAG,
"The array 'parameters' has the wrong dimensions("
+ strings.length + ") in " + method + "("
+ parameters.toString() + ")");
}
}
}
url += "?" + params;
if (url.length() >= 1024) { // The URL will be truncated if it is more
// than 1024
return Communications.connectPOST(hostNameOrIP, webService,
classOrEndPoint, method, parameters);
}
final StringBuffer text = new StringBuffer();
HttpURLConnection conn = null;
InputStreamReader in = null;
BufferedReader buff = null;
try {
final URL page = new URL(url);
conn = (HttpURLConnection) page.openConnection();
conn.connect();
in = new InputStreamReader((InputStream) conn.getContent());
buff = new BufferedReader(in);
String line;
while (null != (line = buff.readLine()) && !"null".equals(line)) {
text.append(line + "\n");
}
} catch (final Exception e) {
Log.e(Standards.TAG,
"Exception while getting " + method + " from " + webService
+ "/" + classOrEndPoint + " with parameters: "
+ params + ", exception: " + e.toString()
+ ", cause: " + e.getCause() + ", message: "
+ e.getMessage());
Standards.stackTracePrint(e.getStackTrace(), method);
return null;
} finally {
if (null != buff) {
try {
buff.close();
} catch (final IOException e1) {
}
buff = null;
}
if (null != in) {
try {
in.close();
} catch (final IOException e1) {
}
in = null;
}
if (null != conn) {
conn.disconnect();
conn = null;
}
}
if (text.length() > 0 && Communications.checkText(text.toString())) {
final String temp = Communications.getDataFromXML(text.toString());
Log.i(Standards.TAG, "Success in " + method + "(" + params
+ ") = " + temp);
return temp;
}
Log.w(Standards.TAG, "Warning: " + method + "(" + params + "), text = "
+ text.toString());
return null;
}
let's say this url makes your service shows it's output
http://google.com/wcfsvc/service.svc/showuserdata/11949
public boolean isWSTrue() {
String data = connectGET("google.com",
"wcfsvc", "service.svc",
"showuserdata/11949", null);
if(null != data && data.length() >0)
return data.toLowerCase().contains("true");
throw new Exception("failed to get webservice data");
}
Note: that within this case you do not actually need to parse the JSON or XML if only checking for boolean then you know if you found true it's true if found anything else it's false.
if you need to get data using XML or JSON you can refer to this answer https://stackoverflow.com/a/3812146/435706

Every second HttpsUrlConnection request of my static method fails on Android

I'm having a big issue with a static HTTPS connection method. Every second request fails and HttpsUrlConnection.getResponseCode() returns -1. So every second call works well, returning data as expected.
It's the method of a static class I'm using in different corners of my application. I would guess there is anything I don't clean up correctly when the method returns the first time and that whatever causes a problem might get destroyed through a second call of the method. But I'm having a hard time finding any clues.
I'm currently using this class to talk to hosts with invalid SSL certificates. Not going to use this in the final version of the app, but right now I need to save money. ;)
public static String makeInvalidHTTPSRequest(String url, String[] postVars, String userName, String userPass, Context ctx) throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
StringBuffer sb = new StringBuffer();
String serverAuth = null;
String serverAuthBase64 = null;
StringBuffer urlParameters = new StringBuffer();
InputStream rcvdInputStream = null;
if (checkNetworkAvailability(ctx) == false) {
GeneralMethods.writeLog("Network unavailable", 1, GeneralMethods.class);
return null;
}
SSLContext sc = null;
sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new KTPTrustManager() }, new SecureRandom());
GeneralMethods.writeLog("makeInvalidHTTPSRequest-> " + url + ", " + userName + ", " + userPass, 0, GeneralMethods.class);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new KTPHostnameVerifier());
HttpsURLConnection con = null;
con = (HttpsURLConnection) new URL(url).openConnection();
if (userName != null) {
serverAuth = userName + ":" + userPass;
serverAuthBase64 = KTPBase64.encode(serverAuth.getBytes());
}
try {
String[] tmpPair = null;
con.setRequestMethod("POST");
if (serverAuthBase64 != null)
con.setRequestProperty("Authorization", "Basic " + serverAuthBase64);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (postVars != null) {
for (int i = 0; i < postVars.length; i++) {
tmpPair = postVars[i].toString().split("=");
if (i > 0)
urlParameters.append("&" + tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
else
urlParameters.append(tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
}
con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.toString().getBytes().length));
}
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream());
if (postVars != null)
wr.writeBytes (urlParameters.toString());
wr.flush();
wr.close();
if (con.getResponseCode() == 200) {
globalRetries = 0;
rcvdInputStream = con.getInputStream();
}
else if (con.getResponseCode() == 401) {
con.disconnect();
GeneralMethods.writeLog("error 401", 2, GeneralMethods.class);
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
else {
GeneralMethods.writeLog("error - connection response code " + con.getResponseCode() + ": " + con.getResponseMessage() + " (length: "+ con.getContentLength() +")\n\n", 1, GeneralMethods.class);
con.disconnect();
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader(rcvdInputStream), 8192 );
String line;
while ( ( line = br.readLine() ) != null ) {
sb.append(line);
}
con.disconnect();
con = null;
}
catch(Exception e) {
handleException(e, 2, GeneralMethods.class);
}
GeneralMethods.writeLog("makeInvalidHTTPSRequest: Response is \"" + sb.toString() + "\"\n\n", 0, GeneralMethods.class);
if(con != null) {
con.disconnect();
con = null;
}
if (sb.toString().trim() == "")
return null;
else
return sb.toString();
}
Thanks a lot for your help!
Best regards
S.
This might be of help: HttpsURLConnection and intermittent connections

Categories

Resources