使用httpclient获取数据的问题

Problem with using httpclient for fetching data

我想在我的 android 应用程序中使用 httpclient。我知道这个库很久以前就被弃用了,但出于某种原因我想使用它。当我编写一些代码从 URL 中获取 JSON 数据时,模拟器获取了我这个:image

这是我的代码:

public class FirstExampleActivity extends AppCompatActivity {

TextView tv ;
public static final String URL = "http://androidtestapp.gigfa.com/mysite/guitarist.json";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first_example);

    tv = findViewById(R.id.tv);
}

@Override
public boolean onCreateOptionsMenu(final Menu menu) {

    MenuItem item = menu.add("GET");
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

            Thread thread = new Thread(new Runnable() {

                Handler handler = new Handler(){

                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        String content = msg.getData().getString("content");
                        tv.setText(content);
                    }
                };

                @Override
                public void run() {
                    String content = getData();
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("content",content);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
            });
            thread.start();
            return false;
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private String getData() {

    HttpClient client = new DefaultHttpClient();
    HttpGet method = new HttpGet(URL);
    try{
        HttpResponse response = client.execute(method);
        InputStream stream = response.getEntity().getContent();
        String content = Utils.inputStreamToString(stream);
        return content ;
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return null ;
}
}

我相信这个 可以帮助到你。问题是一些站点起初 return 一些 javascript,例如用于验证目的,但 httpclient 不支持 javascript.

以下代码段应该足够了:

public class FirstExampleActivity extends AppCompatActivity {

   public static final String URL = "http://androidtestapp.gigfa.com/mysite/guitarist.json";
   TextView tv;
   private static final String TAG = FirstExampleActivity.class.getSimpleName();

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       tv = findViewById(R.id.tv);
   }
   @Override
   public boolean onCreateOptionsMenu(final Menu menu) {

       MenuItem item = menu.add("GET");
       item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
       item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
           @Override
           public boolean onMenuItemClick(MenuItem item) {

               Thread thread = new Thread(new Runnable() {

                  Handler handler = new Handler() {

                       @Override
                       public void handleMessage(Message msg) {
                           super.handleMessage(msg);
                           final String content = msg.getData().getString("content");
                           tv.setText(content);
                       }
                   };

                   @Override
                   public void run() {
                       String content = getData();
                       Message message = new Message();
                       Bundle bundle = new Bundle();
                       bundle.putString("content", content);
                       message.setData(bundle);
                       handler.sendMessage(message);
                   }
               });
               thread.start();
               return false;
           }
       });
       return super.onCreateOptionsMenu(menu);
  }

  private String getData() {

      URL client;
      HttpURLConnection urlConnection = null;
      try {
          client = new URL(URL);
          urlConnection = (HttpURLConnection) client.openConnection();
          urlConnection.setRequestMethod("GET");
          int responseCode = urlConnection.getResponseCode();

          if (responseCode == HttpURLConnection.HTTP_OK) { // connection ok
              BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
              String inputLine;
              StringBuilder response = new StringBuilder();
              while ((inputLine = in.readLine()) != null) {
                  response.append(inputLine);
              }
              in.close();
              return response.toString();
          }
      } catch (IOException exc) {
          Log.e(TAG, "exception:" + exc);
      } finally {
          if(urlConnection!=null){
              urlConnection.disconnect();
          }
      }
      return null;
  }
}