我正在尝试从Web服务获取json字符串。我已成功登录并在我的共享偏好中保存了一个cookie。然后使用url / path将cookie传递给getMyAdverts方法以检索json数据。这是我的方法。
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);
}
我的问题是我没有得到任何回应。我是否正确地通过了cookie或者我错过了一步。这是我的日志。
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)
更新:方法2:COOKIE已经过期但是COOKIE应该会在11月16日星期日如何出现
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);
}
}