public static String getJSONfromURL(String URL) {
try {
URL url = new URL("https://www.taxmann.com/TaxmannWhatsnewService/mobileservice.aspx?service=topstories");
HttpsURLConnection connection = (HttpsURLConnection) url
.openConnection();
int code = connection.getResponseCode();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder();
String query = builder.build().getEncodedQuery();
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
connection.connect();
System.out.println(code);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
这是我的代码我试图从服务器获得响应,但它来了异常协议异常连接已经建立我不知道为什么这个异常来了请修复它这个异常在哪里做错了
答案 0 :(得分:0)
您需要在connection.connect()之后移动getResponseCode()。像这样:
URL url = new URL("https://www.taxmann.com/TaxmannWhatsnewService/mobileservice.aspx"); //Remove Query Param from Url
HttpsURLConnection connection = (HttpsURLConnection) url
.openConnection();
// int code = connection.getResponseCode();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("service", "topstories"); //Add this line
String query = builder.build().getEncodedQuery();
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
connection.connect();
//Note that above line is irrelevant. See http://docs.oracle.com/javase/tutorial/networking/urls/connecting.html
int code = connection.getResponseCode();//move it here
System.out.println(code);
if (code == 200) {
StringBuilder content = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null)
content.append(line).append("\n");
bufferedReader.close();
System.out.println(content.toString());
}