gpt4 book ai didi

JAVA:http post 请求

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:44 25 4
gpt4 key购买 nike

我必须向网络服务发送请求以使用用户名和密码对用户进行身份验证。

我对以下发帖请求有疑问:

public String postTest(String action, ConnectionParametrData [] parameters) {
Uri.Builder builder = new Uri.Builder().scheme(scheme).authority(authority).path(action);
uri = builder.build();
BufferedReader in = null;
String ans = null;
HttpPost request = new HttpPost(uri.toString());
HttpClient defaultClient = new DefaultHttpClient();
try {
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new UrlEncodedFormEntity(getValuePairs(parameters)));
HttpResponse response = defaultClient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8192);
StringBuffer sb = new StringBuffer("");
String line = "";
String newLine = System.getProperty("line.separator");
while((line = in.readLine()) != null) {
sb.append(line + newLine);
}
ans = sb.toString();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ans;
}

当我执行此方法时,服务器抛出错误,告知该请求不是发布请求。

但是这个方法非常有效:

private String makePost(String action, ConnectionParametrData [] parameters) throws IOException {
StringBuilder urlBuild = new StringBuilder();
urlBuild.append(scheme).append("://www.").append(authority).append(action);
URL url = new URL(urlBuild.toString());
URLConnection urlConnection = url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream());

String content = getParameters(parameters);
printout.writeBytes(content);
printout.flush();
printout.close();

BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8192);
StringBuffer sb = new StringBuffer("");
String line = "";
String newLine = System.getProperty("line.separator");
while((line = in.readLine()) != null) {
sb.append(line + newLine);
}
in.close();
return sb.toString();
}

比起 URLConecction,我更喜欢使用 HttpClient,有人知道为什么第一种方法不被批准为 POST 吗?

最佳答案

在您的第一个代码片段中,我没有看到您在哪里设置登录名和密码的任何发布参数。

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> {
new BasicNameValuePair("login", "myusername"),
new BasicNameValuePair("password", "somepassword")};
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

您可能想看看这个:http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

关于JAVA:http post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12842430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com