I'm using this tutorial to learn how to connect my app to an API:
基于我的JSONParser看起来像这样:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject json = null;
static String outPut = "";
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
outPut = sb.toString();
Log.e("JSON", outPut);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
json = new JSONObject(outPut);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return json;
}
}
我试图用这个来获取json响应:
String requestType = "author";
String getType = "get-list";
apiURL = apiURL+requestType+"/"+getType;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ConsumerKey", consumerKey));
params.add(new BasicNameValuePair("SharedSecret", sharedSecret));
JSONObject json = jsonParser.getJSONFromUrl(apiURL, params);
我已经使用log.d()来检查apiURL,消费者密钥和共享密钥,它们看起来都很好。 API需要“Post”方法,这就是我使用HttpPost而不是HttpGet的原因。
根据日志JSONObject json = jsonParser.getJSONFromUrl(apiURL, params);
触发空指针异常。我假设是因为api没有返回任何东西,但我可能错了。我看不到任何错误吗?
------编辑:添加了log / stacktrace -----
threadid=1: thread exiting with uncaught exception (group=0x419ffb90)
FATAL EXCEPTION: main
Process: com.library.books, PID: 19156
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.library.books/com.library.books.SplashScreen}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.access$700(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.library.books.libraryDB.getAPIRegions(libraryDB.java:467)
at com.library.books.SplashScreen.updateRegions(SplashScreen.java:90)
at com.library.books.SplashScreen.onCreate(SplashScreen.java:35)
at android.app.Activity.performCreate(Activity.java:5243)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
... 11 more
-----编辑:新日志----- 我将URL和pramas移动到JSONParser.java文件中,而不是将它们包含在getJSONFromUrl()中,我得到一个新的日志。
D/AndroidRuntime(27736): Shutting down VM
W/dalvikvm(27736): threadid=1: thread exiting with uncaught exception (group=0x419ffb90)
D/dalvikvm(27736): GC_FOR_ALLOC freed 378K, 6% free 7731K/8148K, paused 33ms, total 34ms
E/AndroidRuntime(27736): FATAL EXCEPTION: main
E/AndroidRuntime(27736): Process: com.library.books, PID: 27736
E/AndroidRuntime(27736): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.library.books/com.library.books.SplashScreen}: android.os.NetworkOnMainThreadException
E/AndroidRuntime(27736): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
E/AndroidRuntime(27736): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
E/AndroidRuntime(27736): at android.app.ActivityThread.access$700(ActivityThread.java:135)
E/AndroidRuntime(27736): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
E/AndroidRuntime(27736): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(27736): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(27736): at android.app.ActivityThread.main(ActivityThread.java:4998)
E/AndroidRuntime(27736): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27736): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(27736): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
E/AndroidRuntime(27736): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
E/AndroidRuntime(27736): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27736): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(27736): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
E/AndroidRuntime(27736): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(27736): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(27736): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(27736): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
E/AndroidRuntime(27736): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
E/AndroidRuntime(27736): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
E/AndroidRuntime(27736): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
E/AndroidRuntime(27736): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
E/AndroidRuntime(27736): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
E/AndroidRuntime(27736): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
E/AndroidRuntime(27736): at com.library.books.JSONParser.getJSONFromUrl(JSONParser.java:46)
E/AndroidRuntime(27736): at com.library.books.libraryDB.getAPIRegions(libraryDB.java:467)
E/AndroidRuntime(27736): at com.library.books.SplashScreen.updateRegions(SplashScreen.java:90)
E/AndroidRuntime(27736): at com.library.books.SplashScreen.onCreate(SplashScreen.java:35)
E/AndroidRuntime(27736): at android.app.Activity.performCreate(Activity.java:5243)
E/AndroidRuntime(27736): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(27736): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
E/AndroidRuntime(27736): ... 11 more
-----编辑:新的logcat和脚本-----
logcat的:
D/libEGL(15073): loaded /system/lib/egl/libEGL_tegra.so
D/libEGL(15073): loaded /system/lib/egl/libGLESv1_CM_tegra.so
D/libEGL(15073): loaded /system/lib/egl/libGLESv2_tegra.so
D/dalvikvm(15073): GC_FOR_ALLOC freed 196K, 3% free 7913K/8148K, paused 34ms, total 35ms
D/OpenGLRenderer(15073): Enabling debug mode 0
... the script outputs the json as the html for a 404 page ...
E/JSON Parser(15073): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
D/dalvikvm(15073): GC_FOR_ALLOC freed 187K, 3% free 8239K/8464K, paused 53ms, total 53ms
调用json:
public void getAPIRegions(String appUpdateDate){
String requestType = "author";
String getType = "get-list";
apiURL = apiURL+requestType+"/"+getType;
jsonParser.execute(new String[] {apiURL,consumerKey,sharedSecret});
}
jsonParser,consumerKey,sharedSecret和apiURL在代码的开头启动。
现在的问题是,正如你所看到的那样,“...脚本将json输出为404页面的html ......”
没有像以前那样的错误,现在它正在发回404页面,就像它没有得到ConsumerKey和SharedSecret。