我正在基于android的JSON编写应用程序。我有Wamp Server。我的代码如下...... 在MainActivity中:
public class MainActivity extends AppCompatActivity {
EditText edUsername, edPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edUsername = (EditText) findViewById(R.id.editTextUsername);
edPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void onclickLogin(View v)
{
String username = edUsername.getText().toString();
String password = edPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
和BackgroundWorker类如下:
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://localhost/login.php";
if(type.equals("login"))
{
try {
Log.d("myapp1", "do 1");
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
Log.d("myapp1", "do 2");
OutputStream outputStream = httpURLConnection.getOutputStream();
Log.d("myapp1", "do 3");
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name,"UTF-8") + "&"
+ URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "" ;
String line = "";
while ( (line = bufferedReader.readLine()) != null )
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
@Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
在BackgroundWorker类中,OutputStream方法不起作用...... 我在浏览器中测试了login.php并且它正常工作......但是OutputStream不起作用......请帮助...谢谢。
答案 0 :(得分:0)
localhost
指向同一设备,您正在运行代码。如果您在手机上运行代码,则会引用手机。
localhost
被视为我自己。因此,如果您尝试从手机连接到localhost
,它会尝试连接到手机(本身)。如果您尝试从PC连接,它将连接到 PC (到本身)。
要从手机连接到PC,您必须使用PC IP地址而不是localhost