问题描述
我试图做一些POST参数的服务器的请求,我已经使用了一些code,我发现在这里:How使用java.net.URLConnection中的火灾和处理HTTP请求?
I'm trying to do a request to a server with some POST parameters, I have used some code that I found here: How to use java.net.URLConnection to fire and handle HTTP requests?
问题是,所有的值变为0时,我把它们写出来的服务器上的PHP页面上,除了在SSN的第一个号码。另外,响应我回来了Java code,没有标题的字符集= UTF-8,在内容类型的成员。但你可以在PHP / HTML code看到的,我不随地改变标题。
The problem is that all values becomes "0" when i write them out on the php page on the server, except the first numbers in the ssn. Also, the response i get back to the java code, does not have "charset=UTF-8" in the "content-type" member of the header. But as you can see in the php/html code, I don't change the header anywhere.
Android的code:
Android code:
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;
}
这是我发送请求到页面:
page that i sent the request to:
<!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>
所以,结果我在资源获取变量是HTML code。与00123456insted的组成:
测试
TEST2
123456-7899
So the result I get in the "res" variable is the html code with "00123456" insted of:"TestTest2123456-7899"
这是不是我的领域,所以这将是很好,如果答案(s)是非常容易理解的:)
This is not my field, so it would be nice if the answer(s) is fairly easy to understand :)
在此先感谢!
推荐答案
我已经使用避之不及的URLConnection
,而是一直在使用 DefaultHttpClient
。这里有两个,它发送过GET或POST并返回一个字符串
响应简单的方法
I've stayed away from using URLConnection
and instead have been using DefaultHttpClient
. Here are 2 simple methods which sends off either GET or POST and returns a String
response
要注意的重要组成部分,是在其中添加名称 - >值对 HttpPost
对象: nameValuePairs.add(新BasicNameValuePair(键,params.get(密钥)));
The important part to note is where you add name -> value pairs to the HttpPost
object:nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
httpPost.setEntity(新UrlEn codedFormEntity(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;
}
这篇关于与URLConnection的POST请求,只有数字似乎工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!