从Android应用程序到服务器的HTTP请求
我想从Android应用程序发送名称和姓名到我的服务器。但无法获得连接。我已经使用了大部分可用的代码,但他们都没有工作。以下是我的代码的快照:从Android应用程序到服务器的HTTP请求
private void nextActivity(Profile profile) {
HttpURLConnection con = null;
try {
con = (HttpURLConnection)(new URL("**********/index.php")).openConnection();//not written the url for privacy concern
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
con.getOutputStream().write(("name=" + profile.getFirstName()).getBytes());
con.getOutputStream().write(("surname=" + profile.getLastName()).getBytes());
}
catch (ProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (profile != null) {
Intent main = new Intent(LoginActivity.this, MainActivity.class);
main.putExtra("name", profile.getFirstName());
main.putExtra("surname", profile.getLastName());
main.putExtra("imageUrl", profile.getProfilePictureUri(200, 200).toString());
startActivity(main);
}
}
}
将此代码用作AsyncTask,并解决了我的问题。
class MyAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
String id = params[0], firstname = params[1], lastname = params[2];
URL url = new URL("http://*******index.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8") +
"&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(firstname, "UTF-8") + "&"
+ URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(lastname, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
return null;
}
}
在您的代码中添加这些行并尝试。
con.getOutputStream().flush();
con.getOutputStream().close();
无法正常工作。应用程序开始崩溃 –
首先使用URLEncoder对数据进行编码,然后用输出流进行写入。
已经尝试过。但不工作 –
请分享您收到的错误。 –
我希望你在这里使用的的AsyncTask ... –
检查Internet的权限和尝试ping服务器 – VVB
你得到哪些异常? –