我无法通过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 = new PostFetcher(); fetcher.execute();
关于为什么我收到404错误代码的任何想法,即使网站功能正常?谢谢!
答案 0 :(得分:1)
也许您需要使用HTTP GET代替POST。
答案 1 :(得分:0)
您是否设置了权限
<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;
}
}
祝你好运!