【发布时间】:2016-04-08 11:05:11
【问题描述】:
我正在尝试为网站构建一个 android 应用程序,我需要先在此页面上发布一些价值。 这是我的代码:
private void sendPOST(String user,String pass) throws IOException {
String POST_PARAMS = "username="+user+"&password="+pass;
URL obj = new URL("http://xx.xx.xx.xx/mysite/test.php");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
//----------------------------------------------------------- For POST only - START---------------------------------------------
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// ------------------------------------------------------------For POST only - END----------------------------------------------------
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Toast.makeText(getApplicationContext(), response.toString()==""?"No Result":response.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"POST request failed", Toast.LENGTH_LONG).show();
}
}
当这行被执行时OutputStream os = con.getOutputStream();
发生空异常。
我无法继续进行。请建议我必须采取什么措施来消除此异常。
【问题讨论】:
-
根据目前提供的信息,
con在那个时候不可能抛出 NPE。因此,您更有可能只是误解/误解了问题。因此,如果您编辑问题以粘贴未修改的堆栈跟踪,这将很有帮助,以避免红鲱鱼。 -
java post method in android studio throws exception。不是在 Android Studio 中,而是在您的应用程序中。不是 java 帖子,而是 HttpUrlConnection 帖子。 -
删除 Toast() 语句。它们不能与网络代码一起使用。您在 AsyncTask 或线程中调用此代码?如果没有,你有一个 NetworkOnMainathreadException。
标签: java android nullpointerexception http-post urlconnection