Error 403 forbidden - using HttpURLConnection - authorization issue? - android

I have responseCode = 403.
Do you see any issue in the code below?
I tried every flag in the Base64.encode.
My site woks perfectly fine: once I login in manually from http passing my username/passwd, I'm able to retrieve the JSON data using https.
Do you think I'm correct in suspecting an authorization issue?
URL object = new URL("https://aaaaaa.bb/api/?format=json" );
HttpURLConnection connection = (HttpURLConnection) object.openConnection();
connection.setReadTimeout(60 * 1000);
connection.setConnectTimeout(60 * 1000);
connection.setRequestMethod("GET");
String authorization="xxxxxx#gmail.com:yyyyyy";
String encodedAuth="Basic "+ Base64.encode(authorization.getBytes(), Base64.DEFAULT);
connection.setRequestProperty("Authorization", encodedAuth);
connection.connect();
int responseCode = connection.getResponseCode();

Can you try by setting the content type:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

Related

How to add cookie to url using HttpUrlConnection class in android?

I'm trying to parse the json data from an url, when i try to create connection , it throws the exception as
java.net.ProtocolException: cannot write request body after response has been read
I got the response message as Not found.
and i checked the url in web browser it shows the Json data when i login wuth my credentials.
so, i found that i need to add the cookie to my connection, but i don't know how to do this.
public void parseData(String cookie){
HttpUrlConnection connection;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie", cookie);
Log.e(TAG, "cookie " + cookie);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
Log.e(TAG,connection.getResponseMessage());
/**
here i'm trying to parse the data
using BufferedReader calss
**/
}
catch(IOException e){}
}
i need to add the cookie in connection.
Please help me on this.
According to this link
you can do this:
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
Create a cookie string:
String myCookie = "userId=igbrown";
Add the cookie to a request: Using the
setRequestProperty(String name, String value); method, we will add a
property named "Cookie", passing the cookie string created in the
previous step as the property value.
urlConn.setRequestProperty("Cookie", myCookie);
Send the cookie to the server: To send the cookie, simply call connect() on the URLConnection
for which we have added the cookie property:
urlConn.connect()

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

video url Http error 405 can't download

I have an online video url, I can use vitamio video player play it online, but once I use android HttpUrlConnection download, I failed and received http 405 error.Can anyone give me some help?
HttpURLConnection conn = null;
int totalSize = 0;
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(10 * 1000);
conn.setRequestMethod("GET");
conn.connect();
totalSize = conn.getContentLength();
[1]:http://219.238.10.102/videos/v0/20140303/43/4c/69/cd1e834831bfafcdef321e0037050f45.mp4?key=9070001543d27aea&path=/data1/www&m=DC96181615C9D859EB81DA194598DF31A8A3F8DBD9CC94AB612C1489A6574E08E898F5CE76C1BA00DEEE348748C27D82DCCEF4183D058C45DD96616D9D87753F263ADF611C41D0531BA1BDCFD7DE9B16&uuid=4cc6f4b2f1d7b13fa4fd9b4233e0094fc016327ac6ddc126dc54d6f359bcca4b
the url is [the url of a video][1]
I put the url on http://web-sniffer.net/, it displayed right length which is 71917427.
This problem was finally solved by add userAgent:
conn.setRequestProperty("User-agent", "");

post body empty when using httpclient on android

Context: In Android, when I use Java's HttpURLConnection object as shown below, I see the POST body correctly on the server side. However, when I use what I believe is the equivalent HttpClient code, the POST body is empty.
Question:
What am I missing?
Server-side is a Django-python server. I have set up a debug point at the entry point of this endpoint but the post body is already empty. How can I debug through it to find out why the body is null?
Note: I already looked at this , but the solution does not work for me.
Code: using HttpURLConnection - this works:
try {
URL url = new URL("http://10.0.2.2:8000/accounts/signup/");
String charset = "UTF-8";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic base64encodedstring==");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=" + charset);
connection.setDoInput(true);
StringBuilder sb = new StringBuilder();
sb.append("appver=6&user=value1pw=&hash=h1");
OutputStreamWriter outputWriter = new
OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
// handle response
} catch () {
// handle this
}
============================================================
Code: using Apache httpclient - does NOT work - server gets empty POST body:
HttpPost mHttpPost = new HttpPost(""http://10.0.2.2:8000/accounts/signup/"");
mHttpPost.addHeader("Authorization", "Basic base64encodedstring==");
mHttpPost.addHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
mHttpPost.addHeader("Accept-Charset", "UTF-8");
String str = "appver=6&user=value1pw=&hash=h1"; // same as the above
StringEntity strEntity = new StringEntity(str);
mHttpPost.setEntity(strEntity);
HttpUriRequest pHttpUriRequest = mHttpPost;
DefaultHttpClient client = new DefaultHttpClient();
httpResponse = client.execute(pHttpUriRequest);
// more code
I figured the reason why this was happening:
The authorization header in the POST request had an extra new line character "\n" - this was causing the request to go through to the server side handler, but with the body getting cut off. I have never noticed this behavior before.

can't use Http Post method in android application

HI,
I need to use http post method for web-service in android application .But in android shows error when use this method .How to use this method in application or any other equal method for replacing this http post method.
thanks,
Lakshmanan.
URL url = new URL(my_ip_address);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("METHOD", "POST");
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//do your stuff
}

Categories

Resources