代码如下:
package cs;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;
public class Ccs {
HttpURLConnection conn = null;
public String getArea(String phone) {
String area = "";
StringBuffer sb=new StringBuffer();
sb.append("?username="+6666);
sb.append("&password="+7777);
String str = "http://www.baidu.com"+sb;
try {
URL url = new URL(str);
conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput( true );
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/xml");
conn.setRequestProperty( " Content-Length " , String.valueOf(str.length()));
conn.setDoInput( true );
conn.connect();
int code = conn.getResponseCode();
if(code!=200)
{
System.out.println("ERROR==="+code);
}else
{
BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null ) {
area += inputLine + "\n" ;
}
in.close();
}
}catch (Exception ex) {
ex.printStackTrace();
return null;
}
return area;
}
public void cb(){
Ccs t = new Ccs();
String str = "";
str = t.getArea("13682656987");
System.out.println("as:"+str);
}
}
我测试本地可以成功。对于远程地址却不行。高手指点。谢谢。防火墙什么的都关闭了。
异常信息如下:
java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:684)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:554)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:682)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:554)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:936)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:367)
at cs.Ccs.getArea(Ccs.java:33)
at cs.Ccs.main(Ccs.java:59)
as:null
如果把
String str = "http://www.baidu.com"+sb;
改为
String str = "http://127.0.0.1"+sb;
这样就没问题,但是远程地址却出错。