Passing cookie with an HTTT GET - android

I am trying to get a list of user subreddits via the reddit api. Currently I am able to do a post for login which returns a cookie and modhash. Those are the parameters I'm passing to my method below. However each time I call the function I get an empty response:
"{}"
How can I pass a cookie and modhash via HTTPGET to get a valid response?
public void getUserSubreddits(String[] loginInfo){
HttpClient client = new DefaultHttpClient();
URL url = null;
try {
url = new URL("http://www.reddit.com/subreddits/mine/.json?limit=100");
HttpGet httpGet = new HttpGet(String.valueOf(url));
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
httpGet.addHeader("cookie", loginInfo[1]);
httpGet.addHeader("modhash", loginInfo[0]);
HttpResponse response = client.execute(httpGet);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
Log.d(TAG,total.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

It was a simple mistake. To anyone in the future trying this I solved the problem by using Chrome to inspect the headers of an active session on http://www.reddit.com/subreddits/mine/.json?limit=100 url and found that the cookie header started with:
reddit_session
So I removed the modhash changed the my header parameter to read:
httpGet.addHeader("cookie", "reddit_session="+loginInfo[1]+";");
With this I got a valid response.

Related

401 unauthorized error for GET request with type Authorization = bearer token

I am making an HttpGet request with "Authorization" as header attaching bearer token. I am getting a 401 unauthorized error all the time.
I have tried retrofit, it didn't work so I reverted back to basic HTTP client. Then after a lot of research found that there is some error with DefaultHttp. So I changed to HTTPUrlConnection. Even after doing all these, I am still getting an unauthorized 401 error. What could I possibly do wrong here? Because this error still persists, I decided to stick to HTTPUrlConnection or DefaultHTTP and stay away from libraries.
Here is my code with HttpUrlConnection
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)
obj.openConnection();
con.setRequestMethod("GET");
String authString = "Bearer" + accessToken;
con.setRequestProperty("Authorization", authString);
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
System.out.println("GET request not worked");
}
Here is my DefaultHttp request
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(url);
httpGetRequest.addHeader("Authorization","Bearer"+accessToken);
try {
HttpResponse response = client.execute(httpGetRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
add a whitespace after Bearer cus as it stands your concatenating Bearer with the token as one string
Please use Fast Android Networking library its very easy to use and you can implement your logic in less than 5 mins. So please give it a try atleast. Below is the link to library:
https://github.com/amitshekhariitbhu/Fast-Android-Networking
The problem was resolved. I tried using retrofit and defaultHttpClient but both didn't worked for me because of some cookie issue. But using OKHttpClient it was straight forward and I was able to hit the server and get the response.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(mURL)
.addHeader("Authorization", String.format("Bearer %s", bearerToken))
.build();
Response response = client.newCall(request).execute();
return response.body().string();

how to use JSON responce in a url

i am developing an android application with RESTful WebServices
suppose ,
i am sending a url http request as somewebservice/data/access
and is sends data as {"serviceMessageCode":1,"serviceMessageText":"aaaaaa","items":null}
and i want to send another request with that obtained key as
somewebService/rest/services/secure/getcategories?apikey=aaaaaa
int sMC = jsonObj.getInt("serviceMessageCode");
if (sMC == 1) {
smt = jsonObj.getString("serviceMessageText");
can i use somewebService/rest/services/secure/getcategories?apikey=smt
i think i should not do so , some one tell me how to achieve this..!!
please help....
There is no reason why you could not pass some data by GET parameters. It really depends on Rest API on your backend server. Do you use any REST client or base apache http package classes to make requests to server?
Edited:
BufferedReader in = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
String uri = String.format("http://somewebService/rest/services/secure/getcategories?apikey=%s", Config.API_KEY); // API_KEY is constant value written somewhere or could you pass it as method argument
URI website = new URI(uri);
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
StringBuilder builder = new StringBuilder();
while(null != (line = in.readLine())) {
builder.append(line);
}
in.close();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}

Best way to store & use cookies android with HTTPPost & HTTPClient?

I'm coding a login system which will keep the user permanently logged on (until username or password is incorrect) but I'm having an issue with cookie storage. What I want to do is have the cookies store in local storage (probably shared preference). Though I have no idea where to start. This is my main HTTP Post function.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
httppost.setHeader("X-Requested-With", "XMLHttpRequest");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
StringBuffer sb = new StringBuffer();
BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
} catch (Exception e) {
//TODO: WIP
e.printStackTrace();
}
I want to set the cookies first (of course if there are any) then I would like to resave them after the httppost has executed. Where can I go about doing this?
Edit there is about 4 cookies that are saved.
This should help you get started:
http://docs.oracle.com/javase/tutorial/networking/cookies/definition.html
Check out this post as well:
https://stackoverflow.com/a/3587332/2495131

Android Json Get URL STOPPED

I just started the topic to get data from a JSON OpenData and visualize via my phone.
I followed this tutorial and it has worked all :)
https://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html
The url whew i get the datas is :
http:// + api.learn2crack.com/android/json/ (sorry for that, I don't have a good reputation :) )
Then I wanted to try a Opendata me and my android application stops, the url is:
http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16%3A49%3A59.118Z/london.json
You can see it's the same and I only change the name of URL in the code.
You know if the problem is because of the OpenData? and I need some permission? Because when I execute the second part my app stopped
Here, this will work. I am using Strict Policy but normally you should use Async. Please google this as to why we should use Async instead of Strict Policy. This is irrelevant here
When i am using HttpPost to get your json from url, i am getting these errors :-
405 Method Not Allowed
The method POST is not allowed for this resource.
You cannot POST a file
so i am using HttpGet :-
String url = "http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16:49:59.118Z/london.json";
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
JSONObject jObj = new JSONObject(sb.toString());
JSONArray json2 = json.getJSONArray("user");
for (int i = 0; i < json2.length(); i++) {
JSONObject c = json2.getJSONObject(i);
}
}
catch (Exception e) {
e.printStackTrace();
}

Android BufferedInputStream HTTP POST/GET

I Use BufferedInputStream For HTTP POST/GET
But I Get Some Error the Below
java.io.FileNotFoundException: http://XX.XX.XX.XX/WebWS/data.aspx
Transport endpoint is not connected
Why Get This Error. My Code is Below
URL url = new URL(glob.postUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
try {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Language", "TR");
httpConn.setConnectTimeout(12000);
Iterator<String> reqProps = hMap.keySet().iterator();
while (reqProps.hasNext()) {
String key = reqProps.next();
String value = hMap.get(key);
httpConn.addRequestProperty(key, value);
}
InputStream in = new BufferedInputStream(httpConn.getInputStream());
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
httpConn.disconnect();
Thanks.
Is there any reason you're not using HttpClient?
You can replace your code with something like:
HttpContext httpContext = new BasicHttpContext();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String page = EntityUtils.toString(entity);
You can setup the HttpClient with ClientConnectionManager and HttpParams for security and various http parameters for the client at initialisation (plenty of examples around if you search on class names).
HttpURLConnectionImpl.getInputStream() is known to throw a FileNotFoundException if the HTTP response status code is 400 or higher, i.e. for any error condition on the server side. You should check what the status code really is in order to obtain suitable debug information.
However, I second Mark Fisher's suggestion about using HttpClient, which AFAIK is the preferred way of working with HTTP on Android.

Categories

Resources