我正在尝试从ip address
获取URL
,它会在android中返回NULL
,但网址在浏览器中正常工作
代码:
class ipaddress extends AsyncTask<String, String, String> {
Context context;
String ipaddress;
public ipaddress(Context ctx)
{
context = ctx;
}
@Override
protected void onPostExecute(String result) {
if (result == null)
{
Toast.makeText(context, "null", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "not null", Toast.LENGTH_SHORT).show();
}
}
@Override
protected String doInBackground(String... params) {
String web_url = "https://api.ipify.org/?format=json";
try {
URL url = new URL(web_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String verification_data = URLEncoder.encode("format", "UTF-8") + "=" + URLEncoder.encode("json", "UTF-8");
bufferedWriter.write(verification_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bfreader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bfreader.readLine()) != null)
{
result += line;
}
bfreader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
调用方法:
ipaddress ip = new ipaddress(getActivity());
ip.execute();
当我在浏览器中打开URL
时,我得到了准确的结果,但是当我使用此代码访问Android上的URL
时,它返回NULL
请告诉我我犯了什么错误。
答案 0 :(得分:0)
我没有足够的声誉来评论,所以决定使用答案。除非你学习以便熟悉Java和Android,否则我建议你使用像OkHttp by Square这样的库。它使您的工作变得更加容易。