I'm writing a mod for a game in Java to check to see if the player has voted using a server methods to get the Steam ID. I can't get a good response from what I'm seeing. Every response is an IOException which I've had print out "Invalid Response Code".
I've tried implementing what I've seen in similar mods for https connections, but I am not getting anywhere with it.
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL( "https://somewebsite.com/"
).openConnection();
connection.setSSLSocketFactory(createTrustAllSocketFactory());
int responseCode = connection.getResponseCode();
if (responseCode != 200) throw new IOException("Invalid response code.");
InputStream in = connection.getInputStream();
ByteArrayOutputStream stringBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int len = 0;
while (len != -1) {
stringBuffer.write(buffer, 0, len);
len = in.read(buffer);
}
String result = new String(stringBuffer.toByteArray(), StandardCharsets.UTF_8);
if (result.equals("1")) {
try {
performer.addMoney(MonetaryConstants.COIN_COPPER * 5);
performer.getCommunicator().sendNormalServerMessage("Thanks for voting! Your rewards have been added to your bank.");
} catch (IOException ex) {
performer.getCommunicator().sendAlertServerMessage("Failed to add reward. Please submit a support ticket.");
ex.printStackTrace();
}
}
private static SSLSocketFactory createTrustAllSocketFactory() throws IOException {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = {
new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
/* empty */
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
/* empty */
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
ctx.init(null, trustManagers, null);
return ctx.getSocketFactory();
} catch (GeneralSecurityException ex) {
throw new IOException(ex);
}
}
The expectation is that when the command is issued in-game, the server will call the external site with the player's steam ID and generate either a 0 or 1 based on if they have voted.
Actual is getting a bad response code.
Related
I'm making a java program and I want to fetch updates (json data) from URL of my website.
I used HttpURLConnection and Pass SSL Certificate.
I got this error while running:
javax.net.ssl.SSLException: Received fatal alert: internal_error
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2011)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1113)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1391)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1375)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
(HTTPS URL)
I also try HTTP URL but the response code is 308
Pass SSL Certificate code:
public static void setupIgnoreSSLCertificate() throws NoSuchAlgorithmException, KeyManagementException {
final TrustManager[] trustManager = new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}};
final SSLContext disease = SSLContext.getInstance("SSL");
disease.init(null, trustManager, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(disease.getSocketFactory());
final HostnameVerifier aids = (s, sslSession) -> true;
HttpsURLConnection.setDefaultHostnameVerifier(aids);
}
fetch code:
StringBuilder text = new StringBuilder();
try {
setupIgnoreSSLCertificate();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
try {
URL url = new URL(base + method);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if(code != 200) {
System.out.println("Error code: " + code);
} else {
Scanner scanner = new Scanner(url.openStream());
while(scanner.hasNext()) {
text.append(scanner.nextLine());
}
scanner.close();
}
} catch(Exception e) {
e.printStackTrace();
}
In my application I use HttpUrlConnection to upload file to server, when I want to upload a large file, nginx give me a 413 exception code, but HttpUrlConnection's getResponseCode can't catch the exception, I got another exception message.
Here is the exception message:
error asyncExecute:Write error: ssl=0x7ec7b80008: I/O error during system call, Connection reset by peer
Here is my code:
URL originUrl = new URL(url);
String protocol = originUrl.getProtocol();
if (TextUtils.equals(protocol, "http")) {
port = 80;
}
mURL = new URL(protocol, originUrl.getHost(), port, originUrl.getFile());
mConn = (HttpURLConnection) mURL.openConnection();
if (mConn instanceof HttpsURLConnection) {
selfSignedCertificate = true;
SSLCustomSocketFactory factory = new SSLCustomSocketFactory(selfSignedCertificate ? SSLCustomSocketFactory.getSocketFactory()
: (SSLSocketFactory) SSLSocketFactory.getDefault());
((HttpsURLConnection) mConn).setSSLSocketFactory(factory);
((HttpsURLConnection) mConn).setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
mConn.setRequestMethod("POST");
mConn.setDoOutput(true);
mConn.setDoInput(true);
mConn.setUseCaches(false);
mConn.setConnectTimeout(30000);
mConn.setReadTimeout(30000);
mConn.setRequestProperty("User-agent", "xxxx");//xxxx涉及到项目中信息不展示
mConn.setRequestProperty("Connection", "Keep-Alive");
mConn.setRequestProperty("Charset", "UTF-8");
mConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
mConn.setRequestProperty("Expect", "100-Continue");
mConn.setChunkedStreamingMode(0);
//request headers
for (Map.Entry<String, String> item : headers.entrySet()) {
mConn.setRequestProperty(item.getKey(), item.getValue());
}
mConn.connect();
//get outputStream
DataOutputStream out = new DataOutputStream(connect.getOutputStream());
//write params
out.write(params.getBytes());
out.flush();
StringBuffer strBuf = new StringBuffer();
for (String key : paramsMap.keySet()){
strBuf.append(TWO_HYPHENS);
strBuf.append(BOUNDARY);
strBuf.append(LINE_END);
strBuf.append("Content-Disposition: form-data; name=\"" + key + "\"");
strBuf.append(LINE_END);
strBuf.append("Content-Type: " + "text/plain" );
strBuf.append(LINE_END);
strBuf.append("Content-Length: "+paramsMap.get(key).length());
strBuf.append(LINE_END);
strBuf.append(LINE_END);
strBuf.append(paramsMap.get(key));
strBuf.append(LINE_END);
}
String paramsString = strBuf.toString();
out.write(paramsString.getBytes());
out.flush();
String fileName = UriUtils.getFileNameByUri(mContext, fileUri);
String mimeType = UriUtils.getMimeType(mContext, fileUri);
long fileLength = UriUtils.getFileLength(mContext, fileUri);
if(!TextUtils.isEmpty(filename)) {
fileName = filename;
}
//add file headers
out.write(getFileHeaderParamsString(fileKey, fileName, mimeType, fileLength).getBytes());
//add file body
String filePath = UriUtils.getFilePath(fileUri);
InputStream in = null;
try {
if (!TextUtils.isEmpty(filePath) && new File(filePath).exists()) {
in = new FileInputStream(new File(filePath));
} else {
in = mContext.getContentResolver().openInputStream(fileUri);
}
byte[] tmp = new byte[2048];
int l;
long sum = 0;
while ((l = in.read(tmp)) != -1) {
out.write(tmp, 0, l);
sum += l;
if (callback != null) {
callback.onProgress(fileLength, sum);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
//add file end
out.write(getFileEndString().getBytes());
out.flush();
HttpResponse response = new HttpResponse();
//can't get response code here
response.code = mConn.getResponseCode();
if(response.code == HttpURLConnection.HTTP_OK) {
response.contentLength = mConn.getContentLength();
response.inputStream = mConn.getInputStream();
response.content = parseStream(response.inputStream);
}else {
response.errorStream = mConn.getErrorStream();
response.content = parseStream(response.errorStream);
}
......
public static class SSLCustomSocketFactory extends SSLSocketFactory {
private static final String TAG = "SSLCustomSocketFactory";
private static final String[] TLS_SUPPORT_VERSION = {"TLSv1.1", "TLSv1.2"};
private static final String KEY_PASS = "";
final SSLSocketFactory delegate;
static SSLContext sslContext;
static SSLSocketFactory mSocketFactory;
public SSLCustomSocketFactory(SSLSocketFactory base) {
delegate = base;
}
#Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
#Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
#Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return patch(delegate.createSocket(s, host, port, autoClose));
}
#Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port));
}
#Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port, localHost, localPort));
}
#Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return patch(delegate.createSocket(host, port));
}
#Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return patch(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket patch(Socket s) {
if(s instanceof SSLSocket) {
((SSLSocket) s).setEnabledProtocols(TLS_SUPPORT_VERSION);
}
return s;
}
public static synchronized SSLSocketFactory getSocketFactory() {
if(mSocketFactory == null) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
AssetManager am = context().getAssets();
String[] certsPaths = am.list("xxx_certs");
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
for (int i = 0; i < certsPaths.length; i++) {
String certPath = certsPaths[i];
InputStream caInput = null;
try {
caInput = am.open("xxxx_certs/" + certPath);
Certificate ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
keyStore.setCertificateEntry("ca" + i, ca);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (caInput != null) {
caInput.close();
}
}
}
sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.
getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
sslContext.init(null, tmf.getTrustManagers(), null);
mSocketFactory = sslContext.getSocketFactory();
} catch (Throwable e) {
e.printStackTrace();
}
}
return mSocketFactory;
}
}
Here is the nagix return:
<html>
<head>
<title>413 Request Entity Too Large</title>
</head>
<body>
<center>
<h1>413 Request Entity Too Large</h1>
</center>
<hr>
<center>nginx/1.17.5</center>
</body>
<html>
How I can get the right exception code and exception message?
This is a payload limit determined by the server, there is nothing you can do in your application to accept this payload. You must verify that the format and the amount of data sent is correct.
If the server is yours, you must change the limit. Look at this: How to edit nginx.conf to increase file size upload
I am trying to connect to a URL from a desktop app, and I get the error indicated in the Title of my question. When I check the URL in browser, it works fine though.
The error is coming for getInputStream.
When i further tried to investigate to check what the error is by doing getErrorStream i saw it is giving nullpointerexception.
Please guide.
Below is my code
public void call() throws IOException, ParserConfigurationException, SAXException, TransformerException
{
OutputStreamWriter out = null;
URL url = null;
BufferedReader in = null;
String username = "test";
String password = "test";
String xmlDoc =
String xmlDoc = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?> <document schema=\"mySchema.xsd\"><data><start-date>2012-03-10T00:00:00</start-date><end-date>2017-01-13T10:43:00</end-date></data></document>";
try {
// ----Avoid certificate Error Code Start--------
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
SSLContext sc = null;
try
{
sc = SSLContext.getInstance("SSL");
}
catch (NoSuchAlgorithmException e) {
e.getMessage();
}
try
{
sc.init(null, trustAllCerts, new java.security.SecureRandom());
}
catch (KeyManagementException e) {
e.getMessage();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
url = new URL("https://myURL.com?username="+username+"&password="+password+"&xmlDocument="+xmlDoc+"");
//URLEncoder.encode("https://service.bioguiden.se/mpaallexport.asmx/Export?username="+username+"&password="+password+"&xmlDocument="+xmlDoc+"","UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream());
StringBuffer data = new StringBuffer();
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Dear SO Community of Awesomeness,
I'm building a secure app that deals with sensitive information. The app communicates with my own RESTful API over SSL. I don't want to limit the app to the specific certificate I was issued, but rather to trust only certificates issued by my provider, e.g. Comodo. That way I can extend and reissue the certificate without having to release an app update.
I found a great resource for getting this done here but Android 6 deprecated HttpClient and switched to HttpsURLConnection. Google has their own approach posted here. On implementation, however, I noticed that instead of throwing a "not trusted" exception for a different certificate, it just forced the usage of the local CA cert which is not the behavior I intended.
Does anyone have a reference for trusting only a specific CA using HttpsURLConnection?
OK I solved it, figured I would post the solution in case anyone else hits the same problem. Here is the code to use to get a JSON file using HttpsUrlConnection:
(...)
public static class GetJsonTask extends AsyncTask<Void, Integer, AsyncResponse> {
protected String jsonData;
protected IGetJsonListener listener;
protected Context context = null;
protected String strUrl;
public GetJsonTask(Context c, IGetJsonListener l, String strUrl) {
super();
listener = l;
context = c;
this.strUrl = strUrl;
}
#Override
protected AsyncResponse doInBackground(Void... Void) {
JsonObject jsonObjectResult = new JsonObject();
APIStatus status;
if (isConnected(context)) {
HttpsURLConnection httpsURLConnection=null;
try {
//THIS IS KEY: context contains only our CA cert
SSLContext sslContext = getSSLContext(context);
if (sslContext != null) {
//for HTTP BASIC AUTH if your server implements this
//String encoded = Base64.encodeToString(
// ("your_user_name" + ":" + "your_pwd").getBytes(),
// Base64.DEFAULT);
URL url = new URL(strUrl);
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.setRequestProperty("Content-length", "0");
httpsURLConnection.setUseCaches(false);
httpsURLConnection.setAllowUserInteraction(false);
//FOR HTTP BASIC AUTH
//httpsURLConnection.setRequestProperty("Authorization", "Basic " + encoded);
//THIS IS KEY: Set connection to use custom socket factory
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
//httpsURLConnection.setConnectTimeout(timeout);
//httpsURLConnection.setReadTimeout(timeout);
httpsURLConnection.connect();
status = getStatusFromCode(httpsURLConnection.getResponseCode());
listener.getJsonShowProgress(90);
if (status == APIStatus.OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
JsonParser parser = new JsonParser();
String s = stringBuilder.toString();
jsonObjectResult = (JsonObject) parser.parse(s);
}
} else
status = APIStatus.AUTH_ERROR;
listener.getJsonShowProgress(99);
//THIS IS KEY: this exception is thrown if the certificate
//is signed by a CA that is not our CA
} catch (SSLHandshakeException e) {
status = APIStatus.AUTH_ERROR;
//React to what is probably a man-in-the-middle attack
} catch (IOException e) {
status = APIStatus.NET_ERROR;
} catch (JsonParseException e) {
status = APIStatus.JSON_ERROR;
} catch (Exception e) {
status = APIStatus.UNKNOWN_ERROR;
} finally {
if (httpsURLConnection != null)
httpsURLConnection.disconnect();
}
} else {
status = APIStatus.NET_ERROR;
}
// if not successful issue another call for the next hour.
AsyncResponse response = new AsyncResponse();
response.jsonData = jsonObjectResult;
response.opStatus = status;
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (listener != null)
listener.getJsonStartProgress();
}
#Override
protected void onProgressUpdate(Integer... progress) {
listener.getJsonShowProgress(progress[0]);
}
#Override
protected void onPostExecute(AsyncResponse result) {
listener.getJsonFinished(result.jsonData, result.opStatus);
}
public interface IGetJsonListener {
void getJsonStartProgress();
void getJsonShowProgress(int percent);
void getJsonFinished(JsonObject resJson, APIStatus status);
}
}
private static SSLContext getSSLContext(Context context){
//Mostly taken from the Google code link in the question.
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
AssetManager am = context.getAssets();
//THIS IS KEY: Your CA's cert stored in /assets/
InputStream caInput = new BufferedInputStream(am.open("RootCA.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
//System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext;
} catch (Exception e){
return null;
}
}
public enum APIStatus {
OK("OK.", 200), //all went well
JSON_ERROR("Error parsing response.", 1),
NET_ERROR("Network error.", 2), //we couldn't reach the server
UNKNOWN_ERROR("Unknown error.", 3), //some sh*t went down
AUTH_ERROR("Authentication error.", 401), //credentials where wrong
SERVER_ERROR("Internal server error.", 500), //server code crashed
TIMEOUT("Operation timed out.", 408); //network too slow or server overloaded
private String stringValue;
private int intValue;
private APIStatus(String toString, int value) {
stringValue = toString;
intValue = value;
}
#Override
public String toString() {
return stringValue;
}
}
private static APIStatus getStatusFromCode(int code) {
if (code==200 || code==201) {
return APIStatus.OK;
}else if (code == 401) {
return APIStatus.AUTH_ERROR;
} else if (code == 500) {
return APIStatus.SERVER_ERROR;
} else if (code == 408) {
return APIStatus.TIMEOUT;
} else {
return APIStatus.UNKNOWN_ERROR;
}
}
private static class AsyncResponse {
public APIStatus opStatus;
public JsonObject jsonData;
}
(...)
Usage is fairly straightforward:
public class MyClass implements IGetJsonListener {
(...)
new GetJsonTask(context, this, "https://your.url.com/").execute();
#Override
public void getJsonFinished(JsonObject resJson, APIStatus status) {
//Handle JSON content from web here
(...)
}
(...)
}
I'd love to hear any improvements you have.
My application makes multiple web calls in order to get authentication. I need to store this session in a cookie. I wanted to use Cookie Manager but after doing some research, I found out it is only available to API 9 and above and my application needs to be backward compatible.
I make my web connections using HTTPURLConnection to a secure HTTPS. Quick example of my code
public String iStream_to_String(InputStream is)
{
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
String line;
StringBuilder sb = new StringBuilder();
try
{
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
} catch (IOException e)
{
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
/**
* Trust every server - dont check for any certificate
*/
private static void trustAllHosts()
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]
{ new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return new java.security.cert.X509Certificate[]
{};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
}
} };
// Install the all-trusting trust manager
try
{
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e)
{
e.printStackTrace();
}
}
Then I make a request like so
try
{
url = new URL(url1);
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
InputStream in = new BufferedInputStream(http.getInputStream());
sAuthenticateP1 = iStream_to_String(in);
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
The full authentication is done in 4 steps. I need to have it so the session is remembered throughout the 4 steps. Seeing I can't use CookieManager, I have been looking around for other ways of doing this, but can't seem to find any. Would anyone be able to point me in the right direction.
Thanks in advance!!
Figured it out. Incase anyone else is having similar problem, will give quick outline of code. As I said before mine is a several step authentication process. So after the first request, after you have received a response, take the cookie like so
String cookie = http.getRequestProperty("Cookie");
if (cookie != null && cookie.length() > 0)
{
sCookie = cookie;
Log.v("cookie2", sCookie);
}
sCookie is a static string variable I have set up. Then in the next request, after this line
https = (HttpsURLConnection) url.openConnection();
Just put
https.setRequestProperty("Cookie", sCookie);
https.setRequestMethod("POST");
https.setDoInput(true);
https.setDoOutput(true);
And do the same thing for each request after that requires the session, and it should work fine