为什么这不起作用?我也尝试过使用HttpURLConnection类,但是这也没用。 php页面找不到发布的数据。 注意:我很新用java发布请求。
public static String GetURL(String inUrl, String post) {
String inputLine = "";
try {
if (!inUrl.contains("http")) {
throw new Exception("Invalid URL");
} else {
Log.writeLog(inUrl);
URL url = new URL(inUrl);
//send post
URLConnection connection = url.openConnection();
//connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.connect();
OutputStream wr = connection.getOutputStream();
wr.write(post.getBytes());
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
inputLine = in.readLine();
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
Log.writeLog("Error getting url.");
}
return inputLine;
}
答案 0 :(得分:0)
由于您没有指定错误,因此我很难看到您出错的地方。
但是,我认为使用像HttpClient这样的抽象会容易得多。你的代码看起来像这样:
URI uri = new URIBuilder()
.setURI(inUrl)
.addHeader("Accept-Charset", "UTF-8")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(post);
比处理流和连接的低级细节要清晰得多。