最近调用一个接口,发现httppost请求目标网站会出现405 状态码,原因为 Apache、IIS、Nginx等绝大多数web服务器,都不允许静态文件响应POST请求
所以将post请求改为get请求即可
package com.changyou.test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
//import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.codec.DecoderException;
public class AnimalTest {
public static void main(String[] args) throws IOException {
System.out.println("post请求开始...");
//HttpWebRequest request =
HttpClient client = new HttpClient();
//String url = "http://10.128.36.39:8088/180.96.47.133";
String url = "http://10.128.36.39:8088/servers.txt";
PostMethod postMethod= new PostMethod(url);
GetMethod getMethod = new GetMethod(url);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("anchen", "****"); //密码不可见
getMethod.addRequestHeader("Content-Type"," application/x-www-form-urlencoded;charset = utf-8");
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, creds);
postMethod.setDoAuthentication(true);
//String payload="{{\"gameType\":\"1\",\"cmd\":\"102\",\"worldId\":\"154\",\"logType\":\"item\",\"date\":\"2017-08-17\",\"keyWordOne\":\"\",\"keyWordTwo\":\"\"}}";
String payload = "";
try {
postMethod.setRequestEntity(new StringRequestEntity(payload, "text/html", "utf-8"));
//getMethod.set
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
//client.executeMethod(postMethod);
client.executeMethod(getMethod);
} catch (HttpException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//System.out.println(postMethod.getStatusCode());
//System.out.println(postMethod.getResponseBodyAsString());
System.out.println(getMethod.getStatusCode());
//System.out.println(getMethod.getResponseBodyAsString());
System.out.println(new String(getMethod.getResponseBody(), "UTF-8"));
/*postMethod.addRequestHeader("Content-Type"," application/x-www-form-urlencoded;charset = utf-8");
postMethod.setRequestBody("");
try {
client.executeMethod(postMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String result = "";
try {
result = new String(postMethod.getResponseBody(),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("result:"+result);*/
postMethod.releaseConnection();
getMethod.releaseConnection();
}
}