Java Apache HTTP客户端Post似乎正常工作,但未收到变量
我有以下代码来执行httpclient post请求Java Apache HTTP客户端Post似乎正常工作,但未收到变量,java,php,web-services,post,apache-commons-httpclient,Java,Php,Web Services,Post,Apache Commons Httpclient,我有以下代码来执行httpclient post请求 public void upload() throws Exception{ //HTTP POST Service try{ HttpClient httpclient = HttpClientBuilder.create().build(); URI uri = new URIBuilder() .setScheme("http")
public void upload() throws Exception{
//HTTP POST Service
try{
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.mysite.com")
.setPath("/mypage.php")
.setParameter("Username", userID)
.setParameter("Password", password)
.build();
HttpPost httppost = new HttpPost(uri);
httpclient.execute(httppost);
BasicHttpContext localContext = new BasicHttpContext();
HttpResponse response = httpclient.execute(httppost, localContext);
HttpUriRequest currentReq = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost)localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
String currentUrl = currentHost.toURI() + currentReq.getURI();
System.out.println(currentUrl);
System.out.println(response);
HttpEntity httpEntity = response.getEntity();
String str = "";
if (httpEntity != null) {
str = EntityUtils.toString(httpEntity);
System.out.println(str);
}
}catch (Exception e) {
e.printStackTrace();
}
}
返回
HTTP/1.1 200 OK [Date: Sat, 11 Jan 2014 16:17:22 GMT, Server: Apache, Expires: Thu, 19 Nov 1981 08:52:00 GMT, Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, Pragma: no-cache, Vary: Accept-Encoding, Keep-Alive: timeout=10, max=30, Content-Type: text/html, Via: 1.1 NDC1-B2-CE01, Connection: keep-alive]
好像一切都很好,但另一端的php脚本似乎没有接收到变量
我试过一些简单的方法,比如:
<?php
error_log($_POST["Username"]);
?>
但是得到一个索引未定义的错误打印出来您正在设置URI的查询参数,它构建了一个URI,就像您的URI一样
您需要使用NameValuePair
设置HttpPost的参数
HttpPost post = new HttpPost("http://www.mysite.com/mypage.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", userId));
params.add(new BasicNameValuePair("Password", pass));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = post.execute(post);
HttpPost=新的HttpPost(“http://www.mysite.com/mypage.php");
List params=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,userId));
参数添加(新的BasicNameValuePair(“密码”,pass));
post.setEntity(新的UrlEncodedFormEntity(params));
HttpResponse response=post.execute(post);
此外,我建议使用
授权
头处理身份验证,例如通过HTTPS发送凭据。hmm会给我与以前相同的错误吗?您可以发布一个使用基本身份验证的示例吗?然后您可以检索用户名并使用$\u server['PHP\u AUTH\u USER']和$\u server['PHP\u AUTH\u PW']传递服务器端