0

我编写了应该发送用户名并传递给 url 的程序,但是当我运行程序时,程序出现运行时错误。我不知道为什么以及如何解决这个问题?

logCat 中的错误是 java.lang.NullPointerException: println needs a message

GetFromUrl.java

 @SuppressLint("NewApi")
class GetFromURL extends AsyncTask<String,Void, String> {

InputStream is = null;


@Override
protected String doInBackground(String... urls) {

    URL url=null;
    String response=null;
    String parameters=null;
    OutputStreamWriter request=null;


    try {
        url = new URL("http://myurl.com/");
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        Log.i("catch1", "of get");
        e1.printStackTrace();

    }

    try {
        HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
        urlConnection.setDoOutput(true);
        //setRequestProperty();
        urlConnection.setRequestMethod("GET");
        request=new OutputStreamWriter(urlConnection.getOutputStream());
        request.write("UserName=user&Password=pass");
        InputStreamReader inStream=new InputStreamReader(urlConnection.getInputStream());
        response=convertStreamToString(inStream);
    inStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.i("catch2", "of get");
        e.printStackTrace();

    }
    return response;
  }
   private static String convertStreamToString(InputStreamReader is) {
    BufferedReader reader = new BufferedReader(is);
    StringBuilder sb = new StringBuilder();

    String line ="";
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        Log.i("catch3", "of get");
        e.printStackTrace();

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.i("catch4", "of get");
            e.printStackTrace();
        }
    }
    return sb.toString();
}


  }

MainActivity.java

public class MainActivity extends Activity {
      @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button.setOnClickListener(onClickListener);        
     }
private OnClickListener onClickListener=new OnClickListener(){
    public void onClick(View v){
          AsyncTask<String, Void, String> async;
          String result="test";
          async=new GetFromURL().execute("U="+user+"&K="+pass);
            try {
                result = async.get();
                Log.i("RESULT", result);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                Log.i("catch1", "of main");
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                Log.i("catch2", "of main");
                e.printStackTrace();
            }       
    }
   };
}

感谢帮助 。干杯。

4

0 回答 0