我正在尝试向具有一些POST参数的服务器发出请求,我使用了一些我在此处找到的代码:Using java.net.URLConnection to fire and handle HTTP requests
问题是当我在服务器上的php页面上写出它们时,所有值都变为“0”,除了ssn中的第一个数字。此外,我回到java代码的响应,在标题的“content-type”成员中没有“charset = UTF-8”。但是你可以在php / html代码中看到,我不会在任何地方更改标题。
Android代码:
public static String testCon()
{
String url = "http://xxx.xxx.se/postReciverTest.php";
String charset = "UTF-8";
String param1 = "Test";
String param2 = "Test2";
String param3 = "123456-7899";
// ...
String query = null;
try
{
query = String.format("fname=%s&sname=%s&ssn=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset),
URLEncoder.encode(param3, charset));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = new URL(url).openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = null;
try {
try {
output = connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
output.write(query.getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
InputStream response = null;
try {
response = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
int status;
try {
status = ((HttpURLConnection) connection).getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
String contentType = connection.getHeaderField("Content-Type");
charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
charset = "UTF-8"; //this is here just because the header don't seems to contain the info and i know that the charset is UTF-8
String res = "";
if (charset != null) {
BufferedReader reader = null;
try {
try {
reader = new BufferedReader(new InputStreamReader(response, charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
for (String line; (line = reader.readLine()) != null;) {
// ... System.out.println(line) ?
res += line;
}
} catch (IOException e) {
e.printStackTrace();
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
} else {
// It's likely binary content, use InputStream/OutputStream.
}
return null;
}
我发送请求的页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
Test
<?
echo $_POST["fname"] + "<br />";
echo $_POST["sname"] + "<br />";
echo $_POST["ssn"] + "<br />";
?>
</body>
</html>
所以我在“res”变量中得到的结果是带有“00123456”的html代码: “测试 TEST2 123456-7899"
这不是我的领域,所以如果答案很容易理解会很好:)
提前致谢!
答案 0 :(得分:1)
我没有使用URLConnection
而是使用DefaultHttpClient
。以下是两种简单的方法,可以发送GET或POST并返回String
响应
需要注意的重要部分是添加名称的位置 - &gt;值对HttpPost
对象:
nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
以下是一个例子:
Map<String, String> params = new HashMap<String, String>(3);
params.put("fname", "Jon");
params.put("ssn", "xxx-xx-xxxx");
params.put("lname", "Smith");
...
String response = execRequest("http://xxx.xxx.se/postReciverTest.php", params);
-
public static String execRequest(String url, Map<String, String> params) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = null;
HttpGet httpGet = null;
if(params == null || params.size() == 0) {
httpGet = new HttpGet(url);
httpGet.setHeader("Accept-Encoding", "gzip");
}
else {
httpPost = new HttpPost(url);
httpPost.setHeader("Accept-Encoding", "gzip");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for(String key: params.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
HttpResponse httpResponse = (HttpResponse)defaultHttpClient.execute(httpPost == null ? httpGet : httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if(null != httpEntity) {
InputStream inputStream = httpEntity.getContent();
Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
if(contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String responseString = Utils.convertStreamToString(inputStream);
inputStream.close();
return responseString;
}
}
catch(Throwable t) {
if(Const.LOGGING) Log.e(TAG, t.toString(), t);
}
return null;
}
public static String convertStreamToString(InputStream inputStream) {
byte[] bytes = new byte[1024];
StringBuilder sb = new StringBuilder();
int numRead = 0;
try {
while((numRead = inputStream.read(bytes)) != -1)
sb.append(new String(bytes, 0, numRead));
}
catch(IOException e) {
if(Const.LOGGING) Log.e(TAG, e.toString(), e);
}
String response = sb.toString();
if(Const.LOGGING) Log.i(TAG, "response: " + response);
return response;
}