Basic auth server response as unauthorized - android

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();

Related

Some character didn't post with Json Post - getting 500 reponse

I have prepared one API, and I want to send one specific data with json posting.
My code works fine during working with Fiddler or site side.
But the problem is why some character didn't send, when we use Android version as a client device.
For example:
string a="mn✈" // correct on any device (android,site,Fiddler,...)
string b="mn✉" //correct on any device except(android) //getting 500 reponse
String requestURL = Utils.SERVER_URL + "PostJsonFeatures";
HttpURLConnection conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject postDataParams = new JSONObject();
postDataParams.put("Features", getAttributes());
postDataParams.put("productId", productId);
postDataParams.put("groupId", catId);
postDataParams.put("brandId", PrefManager.getInstance(context).getCompanyId());
postDataParams.put("languageId", PrefManager.getInstance(context).getLanguageApi());
DataOutputStream printout = new DataOutputStream(conn.getOutputStream ());
printout.write(postDataParams.toString().getBytes());
printout.flush ();
printout.close ();
You can decode to string and pass in url.
String parseString = URLDecoder.decode(URLEncoder.encode(myString, "UTF-8"), "ISO-8859-1");

FileNotFoundException for site with tilde when using httpurlconnection

There is a strange problem when trying post some data to site with tilde.
How could I fix that in Android?
For example, this is my site:
http://host-site.com/~username/form.php
Here is my code for that:
url = new URL(hostSiteString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Host", "myHost");
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0");
urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
urlConnection.setRequestProperty("Accept-Language", "en-US;q=0.7,en;q=0.3");
urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
urlConnection.setRequestProperty("Connection", "keep-alive");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoOutput(true);
BufferedOutputStream bos = new BufferedOutputStream(urlConnection.getOutputStream());
bos.write(readyToken.getBytes(), 0, readyToken.length());
bos.flush();
bos.close();
Found solution, I had to decode my url.
String decode = URLDecoder.decode(hostSiteString);
url = new URL(decode);

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.

HttpsURLConnection setDoOutput(true) isn't working

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);
...

URLEncoded HttpPost with nested parameters

how to post nested parameters using httppost with urlencoding?for example
{
"album": {
"photos":[
{"id":"1"},
{"id":"2"},
{"id":"3"}
]
},
"name":"jhon",
"uid":"abc#gmail.com",
"pwd":"password"
}
how to post the "album" parameters. name,uid,pwd are basic nameValuePairs.
You can go ahead and create json object and then send it as follows
JsonObject jsonObject = /** Create your json Object **/
And then use it to post to the server
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
URL url = //Your URL HERE
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
conn.connect();

Categories

Resources