Android HttpUrlConnection Cannot Post - Error 403 - android

I'm trying to issue a HttpPost against my webservice with spring security csrf.
first, I'm trying to recover the XSRF TOKEN through a GET request, like this
public static CookieManager xcsrfToken() throws IOException{
String token;
URL url = new URL(urlBase);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
CookieManager cookieManager = new CookieManager();
con.connect();
List<String> cookieHeader = con.getHeaderFields().get("Set-Cookie");
if (cookieHeader != null) {
for (String cookie : cookieHeader) {
cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
System.out.println(con.getHeaderFields());
con.disconnect();
return cookieManager;
}
This is what i get from the con.getHeaderFields()
{null=[HTTP/1.1 200 OK], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Content-Language=[pt-BR], Content-Length=[973], Content-Type=[text/html;charset=ISO-8859-1], Date=[Wed, 19 Aug 2015 10:40:18 GMT], Expires=[0], Pragma=[no-cache], Server=[Apache-Coyote/1.1], Set-Cookie=[JSESSIONID=6C9326FBEEA14752068720006F2B5EAA; Path=/webapi/; HttpOnly, XSRF-TOKEN=07cbed7f-834e-4146-8537-0a6b5669f223; Path=/], X-Android-Received-Millis=[1439980819720], X-Android-Response-Source=[NETWORK 200], X-Android-Sent-Millis=[1439980819693], X-Content-Type-Options=[nosniff], X-Frame-Options=[DENY], X-XSS-Protection=[1; mode=block]}
The XSRF-TOKEN is in my cookie, ok!
If I print then with
System.out.println(cookieManager.getCookieStore().getCookies());
I got this
[JSESSIONID=5B1D3E2D3E7B3E1E6572A3839BFF3741, XSRF-TOKEN=4d4048bd-f21c-48c6-895e-5f67523ad963]
Now, I'm trying to issue a POST against the server, like this
public static HttpURLConnection makeRequest(String metodo, String uri, String requestBody) throws IOException{
URL url = new URL(urlBase + uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(!metodo.equals("GET"));
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Cookie", TextUtils.join("," , xcsrfToken().getCookieStore().getCookies()));
con.connect();
InputStream is = con.getErrorStream();
System.out.println(IOUtils.toString(is, "UTF-8"));
System.out.println(con.getHeaderFields());
return con;
}
But the header is comming back without the cookies
{null=[HTTP/1.1 403 Forbidden], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Content-Language=[en], Content-Length=[1149], Content-Type=[text/html;charset=utf-8], Date=[Wed, 19 Aug 2015 10:42:18 GMT], Expires=[0], Pragma=[no-cache], Server=[Apache-Coyote/1.1], X-Android-Received-Millis=[1439980939827], X-Android-Response-Source=[NETWORK 403], X-Android-Sent-Millis=[1439980939811], X-Content-Type-Options=[nosniff], X-Frame-Options=[DENY], X-XSS-Protection=[1; mode=block]}
And it says that don't have a CSRF valid token
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.
In my webservice, the tokens is configured to rename to XSRF-TOKEN because of angularJs.
SOLUTION
public static void getTokens() throws IOException{
URL url = new URL(urlBase);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
cookieManager = new CookieManager();
List<String> cookieHeader = con.getHeaderFields().get("Set-Cookie");
if (cookieHeader != null) {
for (String cookie : cookieHeader) {
String[] tokens = TextUtils.split(cookie, "=");
if (tokens[0].equals("JSESSIONID"))
cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
if (tokens[0].equals("XSRF-TOKEN")) {
String[] tokenValue = TextUtils.split(tokens[1],";");
xsrfTOKEN = tokenValue[0];
}
}
}
con.disconnect();
}
Then, attach it to HttpUrlConnection
con.setRequestProperty("X-XSRF-TOKEN", xsrfTOKEN);

As I have experienced, we would need to submit the token as a request header. Spring expects its name to be X-CSRF-TOKEN by default. But people using AngularJS normally alter it to X-XSRF-TOKEN in Spring Security configuration.
But looking at your code, I couldn't figure out if you are sending that header.
If it would help, here is a snippet from my one project (using RestAssured):
if (xsrfToken != null && !ctx.getRequestMethod().equals(Method.GET))
requestSpec.header("X-XSRF-TOKEN", xsrfToken);

Related

permission_classes preventing Android app from accessing DRF?

I am having trouble developing a Android app that I want to authenticate with Django REST framework to securely access information. I am being successfully issued a REST token but IsAuthenticated remains false for all of my views.
In Django, I have a class based view that responds if both authentication.TokenAuthentication permissions.IsAuthenticated are valid:
class TestAuthView(APIView):
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, format=None):
return GetRestData()
In Android, I acquire a token by POSTing my uname and passwd to the default url: /rest-auth/login/which responds with token: {"key":"c03c1238ab99d91301d34567bda9d417d2b48c0c"}
public static String getResponseFromHttpUrl(String... params) throws IOException {
ArrayList<AbstractMap.SimpleEntry<String,String>> paramssss = new ArrayList<>();
paramssss.add(new AbstractMap.SimpleEntry<>("username", "root"));
paramssss.add(new AbstractMap.SimpleEntry<>("password", "mypass"));
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(3000);
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(paramssss));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next(); //eg. {"key":"c03c1238ab99d91301d34567bda9d417d2b48c0c"}
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
I then store the token and later use it to request some data:
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection urlConnection = url.openConnection();
String authToken = "c03c1238ab99d91301d34567bda9d417d2b48c0c"; //just use a constant string for now..
urlConnection.addRequestProperty("Authorization", "Token " + authToken);
urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
urlConnection.connect();
...
process the response
...
Looking at the Django logs I see that login succeeds but the GET request fails with HTTP_401_UNAUTHORIZED:
[08/Oct/2019 22:18:53] "POST /rest-auth/login/ HTTP/1.1" 200 50
[08/Oct/2019 22:18:53] "GET /update/ HTTP/1.1" 401 58
When I change the permission_classes to AllowAny:
class TestAuthView(APIView):
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.AllowAny,) //Changed this!!!
def get(self, request, format=None):
return GetRestData()
The response contains the expected REST data and everything succeeds:
[08/Oct/2019 22:24:57] "POST /rest-auth/login/ HTTP/1.1" 200 50
[08/Oct/2019 22:25:02] "GET /update/ HTTP/1.1" 200 19451876
I don't understand how I should properly authenticate my Android app so that IsAuthenticated will not always be False?
Currently I submit a username and password to /rest-auth/login/ and am issued a rest token. But must I also login somewhere else to get a CSRF token and use that as well?
I am not familiar with the need for permissions.IsAuthenticated and if it is even valid for Android apps? I mean do I just leave the permission as AllowAny for non-browser Android apps? I feel it's a bad idea..?
I've been plugging at this for a few days and would kindly appreciate any help!

Firebase Notification with WordpressPlugin

I want to register a device with my Wordpress plugin. For this the Plguin uses the following code.
Sample request for new registration:
POST /pnfw/register/ HTTP/1.1
Host: yoursite
Content-Length: 26
Content-Type: application/x-www-form-urlencoded
token=new_device_id&os=iOS
Returns:
200 OK: on success.
401 Unauthorized: if OAuth is enabled but the signature is invalid (see below).
404 Not Found: if prevToken is not found on updating registration.
500 Internal Server Error: on missing mandatory parameters, unknown operating system, or general failure.
On errors:
On errors, besides the HTTP status codes defined above, a JSON is returned with this format:
This is the class the device registers with Firebase.
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
private static final String REG_TOKEN = "REG_TOKEN";
#Override
public void onTokenRefresh() {
String recent_token = FirebaseInstanceId.getInstance().getToken();
Log.d(REG_TOKEN,recent_token);
sendRegistrationToServer(recent_token);
}
public void sendRegistrationToServer(String recent_token) {
}
}
I can not get the data from "recent_token" to my server.
I tried the whole day.
public void sendRegistrationToServer(String recent_token) throws IOException {
String result = null;
HttpURLConnection urlConnection = null;
try {
String postData = "token=" + recent_token + "&os=Android";
byte[] postDataBytes = postData.getBytes("UTF-8");
URL url = new URL("http://www.bluestarfish.de/pnfw/register/");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("POST", "/pnfw/register/ HTTP/1.1");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("charset", "UTF-8");
urlConnection.setRequestProperty("Host", "www.bluestarfish.de");
urlConnection.setRequestProperty("Content-Length", Integer.toString(postDataBytes.length));
OutputStream out = urlConnection.getOutputStream();
out.write(postDataBytes);
out.close();
//result = readStream(urlConnection.getInputStream());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
//return result;
}
Where is the failure
Unfortunately, nothing happens. Can someone explain the mistake to me?

How to manage Cookies in API 22

I'm looking on how to manage cookies and in particular Csrf token.
But the problem is that all examples I find on the net use deprecated functions in API 22 where Http connections have been widely restructured.
It's not so easy to find our way between all examples using deprecated functions.
I looked at the Android doc http://developer.android.com/reference/java/net/HttpURLConnection.html which seems to be the one matching the HttpUrlConnection to be used in API 22 but when I write the lines:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
Eclipse tells me that CookieManager cannot be instantiated. Why?
Anyway I still don't really see how Cookies will be managed.
Is it so magic??
Do I have to put the lines above in Activity's onCreate() to get the cookies
and in particular csrf token 'automatically' available in all fragments?
Or do have to programmatically insert the cookie in my POST
requests?
EDIT
So I modified my code like that:
first I send a GET request to get the csrfToken back.
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false); // Don't use a Cached Copy
urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
Map<String, List<String>> headers = urlConnection.getHeaderFields();
for (String key: headers.keySet()) {
Log.w("Headers", key + " = " + Arrays.toString(headers.get(key).toArray()));
}
Cookies.saveCookies(urlConnection);
} else {
return null;
}
And I verified that I get and save the csrfToken, between others.
Set-Cookie = [60gpBAK=R1224197954; path=/; expires=Fri, 29-May-2015 17:43:45 GMT, 60gpD=R637403390; path=/; max-age=900, csrfToken=175e1d85c1da067a2ea07b77e2f3b46b2a113620; path=/]
Now, my POST request:
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
Cookies.loadCookies(urlConnection);
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + "UTF-8");
OutputStream output = urlConnection.getOutputStream();
output.write(params.getBytes("UTF-8"));
headers = urlConnection.getHeaderFields();
for (String key: headers.keySet()) {
Log.w("Headers", key + " = " + Arrays.toString(headers.get(key).toArray()));
}
But here the Log.w() ouput is surprising: no setRequestProperty() have modified the headers 'accept-charset' is not present, 'content-type' is not the one I set, nor the cookie either ??? :
05-29 18:27:48.791: W/Headers(11517): null = [HTTP/1.1 411 Length Required]
05-29 18:27:48.791: W/Headers(11517): Connection = [close]
05-29 18:27:48.791: W/Headers(11517): Content-Type = [text/html; charset=iso-8859-1]
05-29 18:27:48.791: W/Headers(11517): Date = [Fri, 29 May 2015 16:27:48 GMT]
05-29 18:27:48.791: W/Headers(11517): Server = [Apache]
05-29 18:27:48.791: W/Headers(11517): Set-Cookie = [60gpD=R637403390; path=/; expires=Fri, 29-May-2015 16:46:01 GMT]
05-29 18:27:48.792: W/Headers(11517): Vary = [Accept-Encoding]
05-29 18:27:48.792: W/Headers(11517): X-Android-Received-Millis = [1432916868791]
05-29 18:27:48.792: W/Headers(11517): X-Android-Response-Source = [NETWORK 411]
05-29 18:27:48.792: W/Headers(11517): X-Android-Sent-Millis = [1432916868760]
What's my mistake here??
Your problem most likely, is due to wrong import.
About question. how does this work. Well those two lines are setting default cookie manager for your whole application, and every UrlConnection call that is called after this initialization will use it.
Try to use following imports and this should work just fine.
import java.net.CookieManager;
import java.net.CookiePolicy;
As site note i should add, that personally i don't like setting global cookie handler and us custom one. (Everything in CookieHelper class)
static CookieManager myCookies;
static {
myCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
}
And methods to save/load to UrlConnection
final public static void saveCookies(HttpURLConnection connection) {
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get("Set-Cookie");
if (cookiesHeader != null && myCookies != null) {
for (String cookie : cookiesHeader) {
try {
cookie = cookie.replace("\"", "");
myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
final public static void loadCookies(HttpURLConnection connection) {
if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
}
}
Example use
HttpURLConnection urlConnection = null;
URL url = new URL(html_url);
urlConnection = (HttpURLConnection) url.openConnection();
Cookies.loadCookies(urlConnection);
urlConnection.addRequestProperty("Cache-Control", "no-cache");
urlConnection.addRequestProperty("Accept-Encoding", "gzip");
urlConnection.connect();
InputStream is = urlConnection.getInputStream();
if (urlConnection.getContentEncoding() != null && urlConnection.getContentEncoding().contains("gzip")) {
GZIPInputStream in = new GZIPInputStream(is);
String out = Tools.inputStreamToString(in, true).toString();
Cookies.saveCookies(urlConnection);
return out;
} else {
String out = Tools.inputStreamToString(is, true).toString();
Cookies.saveCookies(urlConnection);
return out;
}

Android - Login HTTP works API 10 Only

To get some information, my app emulates the behaviour of a web browser. The log-in session of the target website has 3 steps:
Access the form (gives a cookie for authentication)
Send a POST request with all information
The server answers contains a link in the headers that indicates the address to go to
I have three functions for that, one that gets the page and extracts the session Cookie.
The second one extracts the form of this first page and puts the right infos.
The third one prepares the POST request, sends it, and read the Location in the headers.
It works fine... But with API 10 only.......
Does anyone know what has changed after API 10??
I've tried on Emulators with API 13 or more, and at the moment of sending the POST request, the server answers as if the Cookie given in the first page is not valid. (I get an answer Code of 200, and the login page... Instead of a 302 answer and the Location to follow).
I use the java.net CookieManager & CookieHandler
Here is the first function for example:
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
if (MainActivity.cookies != null) {
for (String cookie : MainActivity.cookies) {
conn.setRequestProperty("Cookie", cookie);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
And this is the third function (nothing special in the second one:
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4");
for (String cookie : MainActivity.cookies) {
System.out.println("Adding Cookie: "+cookie);
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
// Update Progress bar -> 25
mProgression += 5;
msg = mHandler.obtainMessage(PROGRESSION, mProgression, 0);
mHandler.sendMessage(msg);
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
System.out.println("Attempt to get location");
// Get the location of the ticket in the ResponseHeader
setLocation(conn.getHeaderFields().get("Location"));
// Get the Cookie of the ResponseHeader AFTER sending credentials
setLoginCookies(conn.getHeaderFields().get("Set-Cookie"));
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// System.out.println(response.toString());
}
There is no problem with the log cat, the third function can't go past the "get("Location")" since the server doesn't return any location...
Thanks to whoever takes time to answer that one...
Btw, it's my first app :)
Thanks again!
I think you should use a better client that will handle all the headers and the body by itself, you can use android built in HTTP client but it can not persist cookies, or you can use loopj async client that works great.
Actually I published a post that explained how we did it, you can read it here.

HTTPURLConnection - 400 Bad Request

I check this Post. But I don't still understand what the logical error could be. I am still getting this error. I tried to dump the emulator traffic. But I still don't get my head around what the problem could be.
From the traffic dump, this is what Android is sending as request to the server. You can see the response too:
GET /Authenticate/ HTTP/1.1
Authorization: Basic asdfasdfasdfas
Accept-Charset: UTF-8
Host: www.domain.com
User-Agent: Dalvik/1.4.0 (Linux; U; Android 2.3.3; sdk Build/GRI34)
Connection: Keep-Alive
Accept-Encoding: gzip
neQPˆ? 6 6 RT 4VRT 5 E (
» #ÍCl¦'
PÙ[ ˜ároP"8" neQPI " " RT 4VRT 5 E
¼ #ËVl¦'
PÙ[ ˜ároP"8«‹ HTTP/1.1 400 Bad Request
Date: Thu, 13 Sep 2012 04:47:42 GMT
Server: Apache/2.2.15 (CentOS)
Content-Length: 310
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.2.15 (CentOS) Server at www.domain.com Port 80</address>
</body></html>
neQPé¬ 6 6 RT 4VRT 5 E (
½ #ÍAl¦'
PÙ[ ™îároP"8 , neQPéË # # RT 5RT 4V E (çØ# #³-
l¦'Ù[ Páro ™îP )E neQPéË # # RT 5RT 4V E (çÙ# #³,
l¦'Ù[ Páro ™ïP )D neQPö“
© © RT 5RT 4V E ›k‹# #¶Á
³ër,9Jr ‘Pÿÿ6B WRTE w [ * ¨­«º[ 09-13 04:47:41.822 446:0x1c7 D/400 ]
text/html; charset=iso-8859-1Bad Request
I don't know what those extra characters mean. But I was trying to identify the problem from it.
This is the basic code:
String credentials = username + ":" + password;
byte[] toencode = null;
try {
toencode = credentials.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
HttpURLConnection conn = null;
try {
//Utilities.isNetworkAvailable(context);
URL url = new URL(params[0]);
Log.d(params[0],"UR");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Host", "www.domain.com");
conn.setRequestMethod("GET");
conn.setDoOutput(true);
String data = conn.getInputStream().toString();
return data;
}
Any ideas?
Update
I checked Webserver Logs to see if the requests are hitting the server and if there was any problem with the request. This is what I see from error logs:
[Thu Sep 13 10:05:24 2012] [error] [client 91.222.195.132] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /Authenticate/
[Thu Sep 13 23:11:57 2012] [error] [client 91.222.195.132] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /Authenticate/
[Thu Sep 13 23:12:03 2012] [error] [client 91.222.195.132] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /Authenticate/
However I am setting the header property for the request.
Any ideas?
I figured out this myself. Its an issue with the order of setting headers.
Edit: Order I used.
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Host", "myhost.com");
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setConnectTimeout (5000) ;
conn.setDoOutput(true);
conn.setDoInput(true);
I was also facing this issue, but i fixed it by changing my codes, now i am using following lines of codes
BufferedReader reader;
StringBuffer buffer;
String res = null;
try {
URL url = new URL(request_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(40000);
con.setConnectTimeout(40000);
con.setRequestMethod("GET");
con.setRequestProperty("Accept","application/json");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoInput(true);
con.setDoOutput(true);
int status = con.getResponseCode();
InputStream inputStream;
if (status == HttpURLConnection.HTTP_OK) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
reader = new BufferedReader(new InputStreamReader(inputStream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
res = buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
Try this
static final String _url = "http://www.google.com";
static final String charset = "UTF-8";
// to build the query string that will send the message
private static String buildRequestString(String param1,
String param2, String param3, String param4, String param5)
throws UnsupportedEncodingException {
String[] params = new String[5]; //customize this as per your need
params[0] = param1;
params[1] = param2;
params[2] = param3;
params[3] = param4;
params[4] = param5;
String query = String.format(
"uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
URLEncoder.encode(params[0], charset),
URLEncoder.encode(params[1], charset),
URLEncoder.encode(params[2], charset),
URLEncoder.encode(params[3], charset),
URLEncoder.encode(params[4], charset));
return query;
}
public static void doSomething(String param1, String param2,
String param3, String param4, String param5) throws Exception {
// To establish the connection and perform the post request
URLConnection connection = new URL(_url
+ "?"
+ buildRequestString(param1, param2, param3, param4,
param5)).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
// This automatically fires the request and we can use it to determine
// the response status
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
// This stores the response code.
// Any call to br.readLine() after this is null.
responsecode = br.readLine();
// And this logs the already stored response code
Log.d("ServerResponse", responsecode);
responseInt = Integer.valueOf(responsecode).intValue();
}

Categories

Resources