I am writing an application where the user inputs song information that will then be viewed on a website. I am trying to get this HttpGet request to work. I really don't need the server to return any information. I just need the information to store in the MySQL database. On the php side of things I use $_GET to pull the information. Am I approaching this the wrong way? Here is my android code:
public void executeHttpGet() throws Exception{
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
"http://localhost:8888/?title=hello&artist=horray");
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} finally {
开发者_Go百科if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You should really use POST for this instead of GET. You'll have to change your PHP, but since you're inserting data into the database you should not use a GET. That's exactly what POST is for.
Also, "localhost" won't work, since when you're running on the emulator, "localhost" means the phone. On the emulator "10.0.2.2" means your computer. So I'm assuming that's the one you want to use.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("10.0.2.2:8888");
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("title", "hello"));
params.add(new BasicNameValuePair("artist", "horray"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpClient.execute(httpPost);
Log.i("posting", "Saved to server");
} catch (Exception e) {
Log.e("posting", e.getMessage());
}
Hope that helps!
Why not try using a POST instead? Take a look at this article:
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
精彩评论