代码很简单,就是发送一个get请求。
url是没问题的,手动打开获取数据,格式是这样的:
{“msg”:”success”,”code”:0,”money”:0.02,”maxCode”:40,”token”:”BAA8FE9AD2B0B5E04A3832D8B7505B96A3C9″}
但是用代码请求一直不成功,conn.getResponseCode() 根本获取不到状态码。
根本想不明白什么原因。今天我发现写的其他get请求都没成功,以前写的可以
try {
URL url=new URL("http://www.huli667.com:81/sms/api/login?username=api-ArIGbJDn&password=a411724");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code=conn.getResponseCode();
if(code==200){
InputStream in=conn.getInputStream();
String result=ParseStream.readInputStream(in);
System.out.println(result);
}
} catch (MalformedURLException e) {
} catch (ProtocolException e) {
} catch (IOException e) {
}
回答
public static void main(String[] args) {
try {
URL url=new URL("http://www.huli667.com:81/sms/api/login?username=api-ArIGbJDn&password=a411724");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
int code=conn.getResponseCode();
if(code==200){
String res = "",line="";
InputStream in=conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
while( (line = bufferedReader.readLine()) != null )
{
res += line;
}
System.out.println(res);
bufferedReader.close();
in.close();
}
conn.disconnect();
} catch (Exception e){
e.printStackTrace();
}
}
发现用HTTP测试正常,但是用你的代码就不行,然后我加了个请求头参数,
应该是你服务端上面的判断