HttpsURLConnection setDoOutput(true) isn't working - android

So I am currently writing an android app that will get tweets from a particular user, using Twitter's 1.1 Application-only-auth, which requires a POST HTTP request to get a bearer token. I have a method set up that uses an HttpsURLConnection to open a connection, but
conn.setDoOutput(true); method isn't working
conn.doOutput stays false
the request stays the default GET.
Am I doing something wrong?
This method is called in an AsyncTask's doInBackground() method:
public String getRequestBearerToken(String endUrl) throws IOException {
String encodedCred = encodeKeys("API-key", "API-secret");
HttpsURLConnection connection = null;
try {
URL url = new URL(endUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// POST request properties
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", getResources()
.getString(R.string.app_name));
connection.setRequestProperty("Authorization", "Basic "
+ encodedCred);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
...

Related

Basic auth server response as unauthorized

I am new to android, i am using server call for signin with Basic Auth, its all works fine if i login with more than 45 letter in userid server response as Unauthorized. if user id is less than 45 letters its accepting
my server call as follows
HttpURLConnection conn=null;
URL url = new URL(url string);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setReadTimeout(60000);
String basicAuth = "Basic " + new String(Base64.encode(Username+":"+Password));
conn.setRequestProperty ("Authorization", basicAuth);
conn.connect();
Here conn.connect(); itself throws 401 : UnAuthorized
HttpURLConnection conn=null;
URL url = new URL(url string);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(60000);
String publicKey = "Username:Password";//getting your key
String encodedString = Base64.encodeToString(publicKey.getBytes(), Base64.NO_WRAP);
String basicAuth = "Basic "+ encodedString; //space after Basic is matter.
//setting header for authentication purpose, should use authorization as keyword it you change this it won't work anymore
conn.setRequestProperty("Authorization", basicAuth);
conn.connect();
Code as below:
String credentials = String.format("%s:%s", "username", "password");
String basicAuth = "Basic "+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HttpURLConnection conn=null;
URL url = new URL(url string);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setReadTimeout(60000);
conn.setRequestProperty ("Authorization", basicAuth);
conn.connect();

Problems doing a POST request from android

I'm trying to login in a Django server from an android app, from the web it works fine, but when I try to do it from the app I get an Internal Server Error. I'm using HttpURLConnection:
url = new URL(loginUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.getContent();
conn.disconnect();
CookieStore cookieJar = cManager.getCookieStore();
List <HttpCookie> cookies = cookieJar.getCookies();
String csfr = null;
for (HttpCookie cookie: cookies) {
Log.d("cookie", ""+cookie);
if(cookie.getName()=="csrftoken"){
csfr = cookie.getValue();
break;
}
}
String postParams = "csrfmiddlewaretoken="+csfr+"&username="+user+"&password="+pass+"&this_is_the_login_form=1&next=";
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", ""+postParams.getBytes().length);
conn.setRequestProperty("User-Agent","Mozilla/5.0");
conn.setFixedLengthStreamingMode(postParams.getBytes().length);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(postParams);
dos.flush();
dos.close();
Log.d(conn.getResponseCode()+"", ""+conn.getResponseMessage());
The GET request works fine and fetch the csrf cookie just right, I don't know what I'm missing in the POST request. Here's a capture of the data posted from a browser request:
csrfmiddlewaretoken=zqvmoYTLeimB9RW5cMj5xTyLhIzR8kqr&username=user&password=123456&this_is_the_login_form=1&next=
edit:
Finally got it working, diasabled csfr protection, added some RequestProperty, read the response (getting pipe broken error en server side if not read) and added a '/' at the end of the URL. Porbably the causer of all or almost all of the error was the missing '/' on the url.
Final working coding:
url = new URL("http://XX.XXX.XXX.XXX/accounts/login/");
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.getContent();
conn.disconnect();
/*CookieStore cookieJar = cManager.getCookieStore();
List <HttpCookie> cookies = cookieJar.getCookies();
String csfr = null;
for (HttpCookie cookie: cookies) {
if(cookie.getName()=="csrftoken"){
csfr = cookie.getValue();
break;
}
}*/
String postParams = "username=patient1&password=123456";
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Length", ""+postParams.getBytes().length);
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8");
conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setFixedLengthStreamingMode(postParams.getBytes().length);
OutputStream os = conn.getOutputStream();
os.write(postParams.getBytes("UTF-8"));
InputStream is = conn.getInputStream();
while(is.read() > -1);
Log.d(conn.getResponseCode()+"", ""+conn.getResponseMessage());
You might need to disable csrf protection in your django login view.

Android upload file to HttpServer using HTTP POST (File type: httppostedfilebase)

I need to upload file to server using httppost type. In server side they received the file in httppostedfilebase instance.
How to do this? Suggest me.
try this:
url = new URL("http://....");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(stufftosend);
outputStream.flush();
outputStream.close();

SOAP Authentication Android

I am trying to hit this services but this gives me html reponse please help me where i am wrong
any help is really very help ful
HttpURLConnection connection;
java.net.URL u;
u = new java.net.URL("http://sdservices.iyogi.net/iyogi/webservicesnonrestv5/toolbarwebservices.asmx");
URLConnection uc = u.openConnection();
connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("SOAPAction", "http://sdservices.iyogi.net/SD/ToolbarService.svc/GetProductSettings?SubscriptionCode=W101982488");
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "text/xml; charset=utf-8");
InputStream is = connection.getInputStream();
inputStreamToString(is);
gives HTML in response:(

HttpURLConnection disconnect doesn't work in Android

The method disconnect from HttpURLConnection seems not to work properly.
If I execute the following code:
url = new URL("http:// ...");
connection = (HttpURLConnection) url.openConnection ();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// Some code
connection.disconnect();
connection.setDoInput(false); // -> IllegalStateException
I get an IllegalStateException when I call the method setDoInput. The exception says:
Already connected
It sounds like you're trying to reuse the connection? i.e. altering the request properties after you've disconnected from the server, ready to make another connection.
If that is the case, then just create a new HttpURLConnection object.

Categories

Resources