我试图创建一个应用程序来连接Internet和Return Html。 但它不起作用我不知道原因! 请帮我解决我的问题:tnQ
错误: java.lang.NullPointerException:println需要一条消息
我的代码:
package net.learn2develop.http3;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("location", " 0 as start");
InputStream in=null;
int response=-1;
String urlString="http://www.tabnak.ir";
try
{
URL url=new URL(urlString);
URLConnection conn=url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("Not ann HTTP Connection");
try
{
HttpURLConnection httpConn=(HttpURLConnection)conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response=httpConn.getResponseCode();
if(response==HttpURLConnection.HTTP_OK)
{in=httpConn.getInputStream();}
else{
Log.d("location", " 1");
}
TextView intxt=(TextView)findViewById(R.id.mytxt);
intxt.setText(in.toString());
}
catch(Exception ex0)
{
Log.d("e:",ex0.getLocalizedMessage());
}
}
catch(Exception ex)
{
Log.d("location 2 Exception : ", ex.toString());
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
答案 0 :(得分:0)
我建议使用此库http://loopj.com/android-async-http/
有了这个,你只需要放入这段代码,并在onSuccess方法中满足你的需求。
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.tabnak.ir", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});