因此,我一直在尝试检索JSON文件,这些文件基本上是数据库中的帖子。可以从我正在运行的Django REST API中获取它们。我可以访问该网址,并查看网络中任何设备上的可用帖子。但是,我无法检索它们,因此它们可以发布在我的Android应用程序上。
我登录了postExecute
我的AsyncTask
不显示任何JSON对象,是刚刚清空。
它不会在我的logcat中返回任何错误消息,所以我不确定是什么问题。
我正在尝试制作一个原型社交网络类型的东西,其中将帖子存储在我的数据库中的数据库中,并通过API来获取它们。
我正在AsyncTask
用来连接到我的URL并在那里进行处理
Posts.java
public class Posts extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api/");
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendPostsRequest();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
}
}
WSAdapter.java
public class WSAdapter extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendPostsRequest extends AsyncTask<String, String, String> {
// Add a pre-execute thing
HttpURLConnection urlConnection;
@Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
try {
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
}
}
您需要将协议方案添加到您的网址:http://
,https://
或其他任何你需要的。
所以它应该看起来像这样:
postDetailsHelper.callPostDetails("http://192.168.0.18:8000/api/");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句