我想将一些信息从 PHP 发送到 Java。为什么?因为我的服务器上有一个数据库,我使用 PHP 脚本从我的数据库中获取信息。
现在我想用 Java 将该信息发送给我的客户。我该怎么做?
我通过 POST 将信息从 Java 发送到 PHP,它运行良好,但我不知道如何做相反的事情。
你能帮帮我吗?
我看到这段代码,来自 Java 中的 GET 连接...它是否正确?
public String HttpClientTutorial(){
String url = "http://testes.neoscopio.com/myrepo/send.php";
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}
String response = content.toString();
return response;
}
P.S: 我是一个 android 开发者,不是 Java 开发者...
最佳答案
来自 exampledepot: Sending POST request (修改以获取 send.php
的输出。)
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://testes.neoscopio.com/myrepo/send.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
附言这在 Android 上应该可以正常工作。 :)
(我通常import static java.net.URLEncoder.encode
但这是个人喜好问题。)
关于java - 从 PHP 向 Java 发送信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2904269/