Java Android Studio Исключение нулевого указателя в Jaunt Webcrawler

Я пытаюсь запустить простой пример Jaunt с веб-сайта и получил сообщение об ошибке Null Pointer Exception. Я не уверен, что делать, потому что поддержка Jaunt в Android Studio практически не поддерживается. Вот мой код:

public class MainActivity extends AppCompatActivity {

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

    try{
        UserAgent userAgent = new UserAgent();
        userAgent.visit("http://jaunt-api.com/examples/signup.htm");         
    }
    catch(JauntException e){
        System.out.println(e);
    }

}

}

Вот ошибка, которую я получил при запуске:

java.lang.NullPointerException: Attempt to invoke interface method 'void com.android.okhttp.internal.http.Transport.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference

Ошибка была в строке userAgent.visit.

Вот где я получил код: http://jaunt-api.com/jaunt-tutorial.htm

4 ответа

Эта проблема обычно возникает в Android, если вам не удалось сначала подключить HttpURLConnection - или может быть побочным эффектом, если вы забыли добавить разрешение на доступ к Интернету в манифест

Сначала убедитесь, что ваш URL правильный

http://jaunt-api.com/examples/signup.htm 

это определенно неправильный URL

затем

Вот обходной класс для NPE, который вы можете использовать в OkHttp

public class NullOnEmptyConverterFactory extends Converter.Factory {


    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
        return (Converter<ResponseBody, Object>) body -> {
            if (body.contentLength() == 0) return null;
            return delegate.convert(body);
        };
    }
}

В вашем клиентском компоновщике OkHttp сначала добавьте addNetworkInterceptor, порядок имеет значение

Попробуйте добавить разрешения в вашем AndroidManifest.xml:

<uses-permission
     android:name="android.permission.WRITE_EXTERNAL_STORAGE"
     android:maxSdkVersion="18" />
<uses-permission
     android:name="android.permission.INTERNET"
     android:maxSdkVersion="18" />

Попробуй это

try{
  UserAgent userAgent = new UserAgent();
  userAgent.visit("http://jaunt-api.com/examples/signup.htm");

  userAgent.doc.apply(     //fill-out the form by applying a sequence of inputs
    "tom@mail.com",        //string input is applied to textfield
    "(advanced)",          //bracketed string (regular expression) selects a menu item
    "no comment",          //string input is applied to textarea
    1                      //integer specifies index of radiobutton choice
  ); 
  userAgent.doc.submit("create trial account"); //press the submit button labelled 'create trial account'
  System.out.println(userAgent.getLocation());  //print the current location (url)
}
catch(JauntException e){
  System.out.println(e);
}

Убедитесь, что ваши манифесты имеют интернет-разрешение

<manifest xlmns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>

Использование Asynctask

    private class OkHttpHandler extends AsyncTask<String, Void, byte[]> {



            @Override
            protected byte[] doInBackground(String... params) {

            UserAgent userAgent = new UserAgent();
            userAgent.visit("http://jaunt-api.com/examples/signup.htm");

                return null;
            }

            @Override
            protected void onPostExecute(byte[] bytes) {
                super.onPostExecute(bytes);

    try{

      Form form = userAgent.doc.getForm(0);       //get the document's first Form
      form.setTextField("email", "tom@mail.com"); //or form.set("email", "tom@mail.com");
      form.setPassword("pw", "secret");           //or form.set("pw", "secret");
      form.setCheckBox("remember", true);         //or form.set("remember", "on");
      form.setSelect("account", "advanced");      //or form.set("account", "advanced");
      form.setTextArea("comment", "no comment");  //or form.set("comment", "no comment");
      form.setRadio("inform", "no");              //or form.set("inform", "no");
      form.submit("create trial account");        //click the submit button labelled 'create trial account'
      System.out.println(userAgent.getLocation());//print the current location (url)
    }
    catch(JauntException e){                   
      System.err.println(e);
    }

        }
 }

а затем в вашем onCreate просто выполните его

new OkHttpHandler().execute();
Другие вопросы по тегам