【问题标题】:how to pass the parameters to the urlconnection in java/android?如何将参数传递给java/android中的urlconnection?
【发布时间】:2010-03-13 09:29:17
【问题描述】:

我可以使用 HttpUrlConnection 建立连接。下面是我的代码。

client = new DefaultHttpClient();
URL action_url = new URL(actionUrl);
conn = (HttpURLConnection) action_url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("userType", "2");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestMethod(HttpPost.METHOD_NAME);
DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
String content = "username=username1&password=password11";
Log.v(TAG, "content: " + content);
ds.writeBytes(content);
ds.flush();
ds.close();
InputStream in = conn.getInputStream();//**getting filenotfound exception here.**
BufferedReader reader = new BufferedReader(
                new InputStreamReader(in));
StringBuilder str1 = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str1.append(line);
Log.v(TAG, "line:" + line);
}
in.close();
s = str1.toString();

获取文件未找到异常。不知道为什么?

否则给我一些建议,通过代码将用户名和密码参数传递给 url..

【问题讨论】:

  • 只有从输入流中读取后关闭输出流有帮助吗?

标签: java android url stream


【解决方案1】:

HTTPClient 提供了一种更简单的方式来访问 http 资源,而您只想获取响应正文:

HttpGet httpGet = new HttpGet("http://domain.com/path?var1=bla&var2=foo");
HTTPResponse reponse = httpClient.execute(httpGet);
String responseBody = EntityUtils.toString(response.getEntity());

【讨论】:

  • 这段代码很有用。我可以得到htmlsource。但不能使用我的参数登录。如何将操作类设置为 http 响应。
  • 您是否尝试使用基本身份验证?在发出请求之前,您可以像这样传递用户名和密码。 UsernamePasswordCredentials 凭据 = 新的 UsernamePasswordCredentials(用户名,密码); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
  • 在 HttpGet 之前发出您的请求之前。对吗?
  • 你能用准确的答案编辑你的答案吗?我仍然有同样的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 2011-03-05
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多