Httpget with cookie android - android

I am trying to get a json string from a webservice. I have successfully login and saved a cookie in my sharepreference. the cookie is then passed to the getMyAdverts method with a url/path to retrieve the json data. Here is my method.
public static String getMyAdverts( String path, String cookie) throws ClientProtocolException, IOException, JSONException{
String link =path;
System.out.println(link);
String responseBody = null;
HttpGet httpget = new HttpGet(path);
System.out.println("cookie "+cookie);
httpget.addHeader("Cookie", cookie);
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget);
System.out.println("response: "+response);
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
}
My problem is i don't get any response. Have i passed the cookie correctly or did i miss a step. Here is my log.
11-14 11:15:05.246: W/System.err(24636): java.lang.NullPointerException
11-14 11:15:05.246: W/System.err(24636): at application.util.Utils.getMyAdverts(Utils.java:352)
11-14 11:15:05.246: W/System.err(24636): at application.app.applicationMenu$loadingTask.doInBackground(applicationMenu.java:478)
11-14 11:15:05.253: W/System.err(24636): at application.app.applicationMenu$loadingTask.doInBackground(applicationMenu.java:1)
11-14 11:15:05.253: W/System.err(24636): at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-14 11:15:05.253: V/SlidingMenu(24636): changing layerType. hardware? true
11-14 11:15:05.253: W/System.err(24636): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-14 11:15:05.253: W/System.err(24636): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-14 11:15:05.253: W/System.err(24636): at java.lang.Thread.run(Thread.java:856)
UPDATE: METHOD 2 : THE COOKIE IS EXPIRED BUT THE COOKIE SHOULD EXPIRE ON SATURDAY 16 NOVEMBER HOW COME
public static void cookieSession(String url, String cookie) throws ClientProtocolException, IOException{
String responseBody = null;
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie stdCookie = new BasicClientCookie("Cookie",cookie);
cookieStore.addCookie(stdCookie);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,
cookieStore);
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Cookie", cookie);
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
}
}

Related

Foursquare API 404 error: Endpoint not found

I am trying to do a GET request using the foursquare checkin endpoint. I'm getting back a 404 error which is endpoint not found. Any help with why that could be happening would be great!
try {
URI url = new URI("https://api.foursquare.com/v2/user/self/checkins?oauth_token="+TokenStore.get().getToken()+"&v=20140219");
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
is = entity.getContent();
int responceCode = response.getStatusLine().getStatusCode();
Log.i(TAG, "Responce = "+ responceCode);
} catch(Exception e) {
e.printStackTrace();
}
The endpoint is users/self, not user/self, which you have. Just a typo :)

java.lang.OutOfMemoryError on line httpPost.setEntity(new UrlEncodedFormEntity(params)) while sending image in string format in android

I'm trying to upload a image taken by device camera by calling web-service, the server code is in PHP.
First I convert bitmap to string
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageInString = Base64.encodeToString(byteArray, Base64.DEFAULT);
then construct name value pair object
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("image", imageInString));
params.add(new BasicNameValuePair("img_desc", img_desc));
params.add(new BasicNameValuePair("amount", amount));
params.add(new BasicNameValuePair("request_type", "INSERT"));
and then,
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
This code was working properly yesterday, but today I'm getting error java.lang.OutOfMemoryError on line httpPost.setEntity(new UrlEncodedFormEntity(params));
So how to remove this error?
The log-cat is
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:266)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
at java.lang.Thread.run(Thread.java:1020)
Caused by: java.lang.OutOfMemoryError
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:96)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:147)
at java.lang.StringBuilder.append(StringBuilder.java:217)
at org.apache.http.client.utils.URLEncodedUtils.format(URLEncodedUtils.java:165)
at org.apache.http.client.entity.UrlEncodedFormEntity.<init>(UrlEncodedFormEntity.java:71)
at com.network.GetJSONFomURL.getJSONSrtringFromUrl(GetJSONFomURL.java:24)
at com.network.WebServices.uploadImage(WebServices.java:51)
at com.markphoto_activities.UploadActivity$MyAsyncTaskUploadImage.doInBackground(UploadActivity.java:130)
at com.markphoto_activities.UploadActivity$MyAsyncTaskUploadImage.doInBackground(UploadActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:252)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 4 more
Activity com.markphoto_activities.UploadActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#407aafc8 that was originally added here
android.view.WindowLeaked: Activity com.markphoto_activities.UploadActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#407aafc8 that was originally added here
at android.view.ViewRoot.<init>(ViewRoot.java:285)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:152)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
Instead of name value pair, try this code
MultipartEntity reqEntity = new MultipartEntity();
try {
reqEntity.addPart("email", new StringBody(email));
reqEntity.addPart("image", new FileBody(new File(imagePath)));
reqEntity.addPart("img_desc", new StringBody(img_desc));
reqEntity.addPart("amount", new StringBody(amount));
reqEntity.addPart("request_type", new StringBody("INSERT"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
where imagePath is the path of your image file.
and then instead of httpPost.setEntity(new UrlEncodedFormEntity(params)); use
httpPost.setEntity(reqEntity);
An image in string is too much data for mobiles I think. You could use FileEntity instead.
That should take care of your memory problems.

URL error in Android

String temp1=(String)firstname.getText().toString();
String temp2=(String)lastname.getText().toString();
String urlreg="http://localhost/welcome.php?firstname="+temp1+"&lastname="+temp2;
Here firstname and lastname are the editText fields.
I am getting error as below.
LogCat error:
09-11 22:11:09.529: E/AndroidRuntime(1204): FATAL EXCEPTION: main
09-11 22:11:09.529: E/AndroidRuntime(1204): java.lang.IllegalArgumentException: Illegal character in query at index 54: http://localhost/welcome.php?firstname=ji&lastname=kij
The code works fine if I modify it to
String urlreg="http://localhost/welcome.php?firstname="+temp1+"&lastname";
Where am i going wrong?
Before using urlreg you need to url encode it to take out special characters using URLEncoder.encode().
Or you can do Httppost. It'll automatically encode your url.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("var_name", value));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.in/submit.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

StringIndexOutOfBoundsException in android

I am getting the following error:
java.lang.StringIndexOutOfBoundsException: length=13243; regionStart=32; regionLength=-39
at java.lang.String.startEndAndLength(String.java:593)
at java.lang.String.substring(String.java:1474)
at com.dict.XMLParser.getResultFromXML(XMLParser.java:63)
at com.dict.InternetDictProvider.searchWord(InternetDictProvider.java:29)
at com.dict.SearchDict$SearchOnline.doInBackground(SearchDict.java:130)
at com.dict.SearchDict$SearchOnline.doInBackground(SearchDict.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
in the following code which typically gets results after parsing the XML page given as HttpResponse to a HttpGet :
retry:
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://oxforddictionaries.com/definition/"+query+"?q="+query);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String meanings=parser.getResultFromXML(StringUtils.inputStreamToString(httpEntity.getContent()));
if(meanings==null && firstRetry)
{
firstRetry=false;
query = query.substring(0, 1).toUpperCase() + query.substring(1);
break retry;
}
else if(meanings==null && !firstRetry)
return query;
result = query + ":" + meanings;
}
query = query.substring(0, 1).toUpperCase() + query.substring(1);
i think this statement create exeption so use if(null!=query&&query.length()!=0){query=...}
and if you substring your string length more than 1 in your case

not getting response response = httpclient.execute(request);

public class HTTPPoster {
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding((Header) new BasicHeader(HTTP.DEFAULT_CONTENT_CHARSET, "application/json"));
entity = s;
request.setEntity(entity);
HttpResponse response;
response = httpclient.execute(request);
return response;
}
}
This is the code but on response = http.client.execute(request) doesn't get response. I couldn't find why.
You should call the method asynchronously. Then it will work with the same code.
Add these two lines of code to your project
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and
make minimum sdk version to 9
You can check that if you are getting response from server or not by using following code :
HttpResponse response = httpClient1.execute(request);
Log.v("response code", response.getStatusLine()
.getStatusCode() + "");
If you get the value of response code as 200 then you are getting data from server and if the response code value >=300 then you have error at your server side.
First of all try to change the return type to String by doing these 2 steps
Change
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException
to
public static String doPost(String url, JSONObject c) throws ClientProtocolException, IOException
AND
Change
HttpResponse response;
to
String response;
Now check the response string? Is it still null?
This is a permission issue.
Add this line <uses-permission android:name="android.permission.INTERNET" /> to your manifest file and rebuild.

Categories

Resources