我是java编程的初学者。我正在尝试从 url 读取响应并插入数据库。我运行了下面发布的程序,它返回了这个错误:
Exception in thread "main" java.lang.NullPointerException
at javaapp.JavaApplication1.parseResponseString(JavaApplication1.java:41)
at javaapp.JavaApplication1.main(JavaApplication1.java:71)
我一直试图通过研究自己解决这个问题,但我无法解决。我想知道是否有人可以帮助我。如果您确实需要有关我的程序的任何其他信息,请询问。提前致谢!
这是我写的代码
enter code here
包javaapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class JavaApplication1
{
Map<String,String> responseMap=new HashMap<String, String>();
static String input;
public void getResponseFromUrl() throws IOException
{
URL url = new URL("http://localhost:8084/home/Home");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())) ;
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.contains("<h1>"))
{
String input = inputLine;
input = input.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
}
}
}
public void parseResponseString(String input)
{
String params[]=input.split(",");
for(String param:params)
{
String key= param.substring(0,param.indexOf('='));
String value= param.substring(param.indexOf('=')+1,param.length());
responseMap.put(key, value);
System.out.println(param);
}
}
public void insertToDatabase() throws SQLException, ClassNotFoundException
{
Connection conn=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","jai","jaikiran");
String insertQuery = " INSERT INTO value_1 (username1,username2,username3,username4,username5) "+
" values (?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1,responseMap.get("username1"));
pstmt.setString(2,responseMap.get("username2"));
pstmt.setString(3,responseMap.get("username3"));
pstmt.setString(4,responseMap.get("username4"));
pstmt.setString(5,responseMap.get("username5"));
pstmt.executeUpdate();
}
public static void main(String[] args) throws MalformedURLException, IOException, SQLException, ClassNotFoundException
{
JavaApplication1 application =new JavaApplication1();
application.getResponseFromUrl();
application.parseResponseString(input);//shows exception here
try {
application.insertToDatabase();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in advance,please helpme..