I am trying to send name and surname to my server from an android app. But unable to get the connection. I have used most of the codes available, but none of them are working. Below is the snapshot of my code:
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);
}
}
}
add these lines in your code and try.
con.getOutputStream().flush();
con.getOutputStream().close();
首先使用URLEncoder编码数据,然后使用输出流写入数据。
Used this code as AsyncTask and my problem is solved.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.