我正在尝试从 Web 服务获取 json 字符串。我已成功登录并在我的 sharepreference 中保存了一个 cookie。然后将 cookie 传递给带有 url/路径的 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);
}
}