我很难通过Android应用程序调用API。我使用此网站寻求帮助:http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
当我尝试将URL更改为我想要使用的API时,我得到一个:"服务器响应状态代码:404"。
这是我第一次使用AsyncTask,所以我希望我做得正确。这是我的AsyncTask类:
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public String SERVER_URL = "https://bitpay.com/api/rates";
@Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
Log.i(TAG, "Connected");
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
在onCreate上,我调用:PostFetcher-fetcher=新PostFetcher();fetcher.execute();
有什么想法吗?为什么我会收到404错误代码,尽管网站是正常的?谢谢
也许您需要使用HTTPGET来代替POST。
是否设置权限
<uses-permission android:name="android.permission.INTERNET" />
尝试这种方式
class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public String SERVER_URL = "https://bitpay.com/api/rates";
@Override
protected String doInBackground(Void... params) {
try {
String result ="";
URL myUrl = new URL(SERVER_URL);
HttpURLConnection conn = (HttpURLConnection) myUrl
.openConnection();
//conn.setRequestMethod("POST"); //if you need set POST
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String lineJSON = null;
while ((lineJSON = reader.readLine()) != null) {
sb.append(lineJSON + "n");
}
result = sb.toString();
Log.d(TAG, result);
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
//failedLoadingPosts();
}
return null;
}
}
祝你好运!