[英]trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc
NetworkUtilities.java NetworkUtilities.java
public class NetworkUtilities {公共 class NetworkUtilities {
private static final String TAG = NetworkUtilities.class.getSimpleName();
public static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
}catch (MalformedURLException e){
Log.v(TAG, "Problem building the Url");
}
return url;
}
public static String httpRequest(URL url) throws IOException{
String jsonResponse = "";
if(url ==null){
Log.v(TAG, "Url is null");
return jsonResponse;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200){
inputStream = httpURLConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
else{
Log.e(TAG, "Error response code" + httpURLConnection.getResponseCode());
}
}catch (IOException e){
Log.v(TAG, "Problem retrieving the json result", e);
}finally {
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
if(inputStream != null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader in = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bf = new BufferedReader(in);
String line = bf.readLine();
while(line != null){
output.append(line);
line = bf.readLine();
}
}
return output.toString();
}
public static List<String> extractFromJson(String jsonResponse){
if(TextUtils.isEmpty(jsonResponse)){
return null;
}
List<String> newsStories = new ArrayList<>();
try{
JSONObject baseObj = new JSONObject(jsonResponse);
JSONArray articlesArray = baseObj.getJSONArray("data");
for(int i=0;i<articlesArray.length();i++){
JSONObject currentArticle = articlesArray.getJSONObject(i);
JSONObject source = currentArticle.getJSONObject("source");
String sourceName = source.getString("name");
String title = currentArticle.getString("title");
String description = currentArticle.getString("description");
String newsStory = "Source" + sourceName + "/n" + title + "/n" + description;
newsStories.add(newsStory);
}
}catch (JSONException e){
Log.e(TAG, " Problem parsing the json string", e);
}
return newsStories;
}
NewsAdapter.java新闻Adapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {公共 class NewsAdapter 扩展 RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context mContext;
private List<String> mNewsArticles;
NewsAdapter(Context context){
mContext = context;
}
@NonNull
@Override
public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(mContext)
.inflate(R.layout.news_list_item,parent, false);
view.setFocusable(true);
return new NewsViewHolder(view);
}
@Override
public void onBindViewHolder( NewsViewHolder holder, int position) {
String currentArticle = mNewsArticles.get(position);
holder.mTextView.setText(currentArticle);
}
@Override
public int getItemCount() {
if(mNewsArticles != null){
return mNewsArticles.size();
}
return 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
public NewsViewHolder(@NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position :" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
}
public void setNewsData(List<String> newsData){
mNewsArticles = newsData;
notifyDataSetChanged();
}
MainActivity.java MainActivity.java
public class MainActivity extends AppCompatActivity {公共 class MainActivity 扩展 AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private NewsAdapter mNewsAdapter;
private static final String BASE_URL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=13f428d687714c33a24f34ad6c5***87";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
mNewsAdapter = new NewsAdapter(this);
mRecyclerView.setAdapter(mNewsAdapter);
new FetchNewsArticle().execute(BASE_URL);
}
public class FetchNewsArticle extends AsyncTask<String, Void, List<String>>{
@Override
protected List<String> doInBackground(String... strings) {
String stringUrl = strings[0];
URL url = NetworkUtilities.createUrl(stringUrl);
String json = "";
try{
json = NetworkUtilities.httpRequest(url);
List<String> articles = NetworkUtilities.extractFromJson(json);
return articles;
}catch (Exception e){
e.printStackTrace();
Log.v(TAG, "Problem retrieving data");
return null;
}
}
@Override
protected void onPostExecute(List<String> strings) {
if(strings != null){
mNewsAdapter.setNewsData(strings);
}
}
}
Error错误
W/Zygote: Unable to open libbeluga.so: dlopen failed: library "libbeluga.so" not found. W/Zygote:无法打开 libbeluga.so:dlopen 失败:找不到库“libbeluga.so”。 D/NetworkSecurityConfig: No Network Security Config specified, using platform default D/NetworkSecurityConfig: No Network Security Config specified, using platform default W/xample.newsfee: Accessing hidden method Landroid/view/View;
D/NetworkSecurityConfig:未指定网络安全配置,使用平台默认值 D/NetworkSecurityConfig:未指定网络安全配置,使用平台默认值 W/xample.newsfee:访问隐藏方法 Landroid/view/View; >computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) W/xample.newsfee: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) com.example.newsfeed V/NetworkUtilities: Problem retrieving the json result
>computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z(灰名单,反射,允许) W/xample.newsfee:访问隐藏方法 Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V(灰名单,反射,允许)com.example.newsfeed V/NetworkUtilities:检索 json 结果时出现问题
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131) at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49) at com.example.newsfeed.MainActivity$F java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute (HttpURLConnectionImpl.java:462) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131) at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49) at com. example.newsfeed.MainActivity$F etchNewsArticle.doInBackground(MainActivity.java:46) at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38) at android.os.AsyncTask$3.call(AsyncTask.java:394) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:923) 2021-03-11 22:53:28.124 9391
etchNewsArticle.doInBackground(MainActivity.java:46) at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38) at android.os.AsyncTask$3.call(AsyncTask.java:394) at java.util. concurrent.FutureTask.run(FutureTask.java:266) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java. util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:923) 2021-03-11 22:53:28.124 9391 -9391/com.example.newsfeed W/Looper: PerfMonitor looperActivity: package=com.example.newsfeed/.MainActivity time=1ms latency=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running=212ms runnable=80ms io=11ms late=91ms h=android.app.ActivityThread$H w=159) 2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM build: 979eaa0, I11632bc865 Build Date: 11/18/20 OpenGL ES Shader Compiler Version: EV031.32.02.00 Local Branch: Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R1.11.00.00.604.067 Remote Branch: NONE Reconstruct Branch: NOTHING 2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Build Config: SP 10.0.6 AArch64 2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0
-9391/com.example.newsfeed W/Looper:PerfMonitor looperActivity:package=com.example.newsfeed/.MainActivity 时间=1ms 延迟=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running =212ms 可运行=80ms io=11ms 延迟=91ms h=android.app.ActivityThread$H w=159) 2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM构建:979eaa0,I11632bc865 构建日期:2020 年 11 月 18 日 OpenGL ES 着色器编译器版本:EV031.32.02.00 本地分支:远程分支:refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R61.11.00.006 远程分支:无 重建分支:NOTHING 2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0:构建配置:SP 10.0.6 AArch64 2021-03-11 22:53:28.199 9391- 9429/com.example.newsfeed I/AdrenoGLES-0 : Driver Path: /vendor/lib64/egl/libGLESv2_adreno.so 2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000 2021-03-11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: fail to open file: No such file or directory
:驱动程序路径:/vendor/lib64/egl/libGLESv2_adreno.so 2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0:PFP:0x016ee190,ME:0x00000000 2021-03- 11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: 无法打开文件: 没有这样的文件或目录
The error seems to be: java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
. The error seems to be:
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
.
Starting from Android 9, clear text http communication is disabled by default.从 Android 9 开始,明文 http 通信默认禁用。
Check out the official Android documentation for this and also this question for further information.查看官方Android文档以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.