我正在学习如何在android中进行api调用。这是我的片段。我已经在myjson.com上传了这个json文件。从我的片段类中,我尝试着打api。我相信响应应该将json对象内的数据返回到我的日志中。API调用android.os.NetworkOnMainThreadException
public class TableFragment extends android.support.v4.app.Fragment {
public TableFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_table, container, false);
Button api_btn = (Button)rootView.findViewById(R.id.enter_button);
api_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
URL url = new URL("https://api.myjson.com/bins/n80yl");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
Log.d("tagg", "onClick: "+stringBuilder);
}catch (Exception e)
{
Log.d("tagg", "onClick:exception1 "+e);
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.d("tagg", "doInBackground:exception2 "+e);
}
}
});
return rootView;
}
}
我给出了清单中的Internet权限。
这是正确的方式,以便我可以学习android中的api机制。 在此先感谢
这足以执行内部S.O.一些搜索这个问题是Android的基础知识。看看这里https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception –