HttpURLConnection 不起作用
HttpURLConnection doesn't work
我正在尝试在我的 android 项目中使用网络服务数据
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL("http://ip.jsontest.com/");
conn = (HttpURLConnection) url.openConnection();
conn.connect();
int response = conn.getResponseCode(); //fail
Log.d("","success!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
conn.disconnect();
}
调用 conn.getResponseCode()
时代码失败。
调用 conn.getInputStream()
或 conn.getContent()
时也是如此。
没有抛出异常。
conn.disconnect()
(在 finally 块中)在 conn.connect()
之后执行
在我的 AndroidManifest 中我有
<uses-permission android:name="android.permission.INTERNET" />
编辑
我在使用 AsyncTask 时遇到同样的问题
public class DataAccess extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//snackbar.show();
}
@Override
protected String doInBackground(String... strings) {
InputStream inputStream = null;
HttpURLConnection conn = null;
String stringUrl = strings[0];
try {
URL url = new URL(stringUrl);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
int response = conn.getResponseCode();
inputStream = conn.getInputStream();
if (inputStream == null) {
return null;
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
return new String(buffer);
} catch (IOException e) {
return null;
}
finally {
if (conn != null) {
conn.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException ignored) {
}
}
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s == null) {
//resultsTextView.setText("Erreur");
} else {
//resultsTextView.setText(s);
}
//snackbar.dismiss();
}
}
public class example extends AsyncTask<String,String,String>
{
@Override
protected String doInBackground(String... params) {
String link="give the link here";
String data= null;
try {
URL url=new URL(link);
URLConnection conn=url.openConnection();
// 如果你想使用一些值发送一些数据,请使用下面的编码器,否则不需要
数据 = URLEncoder.encode("one", "UTF-8") + "=" + URLEncoder.encode(a, "UTF-8");
data += "&" + URLEncoder.encode("two", "UTF-8") + "=" + URLEncoder.encode(b, "UTF-8");
data += "&" + URLEncoder.encode("three", "UTF-8") + "=" + URLEncoder.encode(c, "UTF-8");
conn.setDoOutput(true);
OutputStreamWriter osw=new OutputStreamWriter(conn.getOutputStream());
osw.write(data);
osw.flush();
osw.close();
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line,sb="";
while((line=br.readLine())!=null)
{
sb+=line;
}
return sb;
}
catch (Exception e)
{
e.printStackTrace();
return new String(e.getMessage().toString());
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// It will get the response from server
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
}
}
响应代码 200 用于成功的 HTTP 请求。
因此,将 if (response != 200)
替换为 if (response == 200)
。
使用 <uses-permission android:name="android.permission.INTERNET" />
更改您的权限。
你有没有得到像线程 StrictMode 这样的东西???
尝试在执行异步任务之前调用它。
https://developer.android.com/reference/android/os/StrictMode.ThreadPolicy.Builder.html
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build(); StrictMode.setThreadPolicy(policy);
我正在尝试在我的 android 项目中使用网络服务数据
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL("http://ip.jsontest.com/");
conn = (HttpURLConnection) url.openConnection();
conn.connect();
int response = conn.getResponseCode(); //fail
Log.d("","success!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
conn.disconnect();
}
调用 conn.getResponseCode()
时代码失败。
调用 conn.getInputStream()
或 conn.getContent()
时也是如此。
没有抛出异常。
conn.disconnect()
(在 finally 块中)在 conn.connect()
在我的 AndroidManifest 中我有
<uses-permission android:name="android.permission.INTERNET" />
编辑
我在使用 AsyncTask 时遇到同样的问题
public class DataAccess extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//snackbar.show();
}
@Override
protected String doInBackground(String... strings) {
InputStream inputStream = null;
HttpURLConnection conn = null;
String stringUrl = strings[0];
try {
URL url = new URL(stringUrl);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
int response = conn.getResponseCode();
inputStream = conn.getInputStream();
if (inputStream == null) {
return null;
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
return new String(buffer);
} catch (IOException e) {
return null;
}
finally {
if (conn != null) {
conn.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException ignored) {
}
}
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s == null) {
//resultsTextView.setText("Erreur");
} else {
//resultsTextView.setText(s);
}
//snackbar.dismiss();
}
}
public class example extends AsyncTask<String,String,String>
{
@Override
protected String doInBackground(String... params) {
String link="give the link here";
String data= null;
try {
URL url=new URL(link);
URLConnection conn=url.openConnection();
// 如果你想使用一些值发送一些数据,请使用下面的编码器,否则不需要 数据 = URLEncoder.encode("one", "UTF-8") + "=" + URLEncoder.encode(a, "UTF-8"); data += "&" + URLEncoder.encode("two", "UTF-8") + "=" + URLEncoder.encode(b, "UTF-8"); data += "&" + URLEncoder.encode("three", "UTF-8") + "=" + URLEncoder.encode(c, "UTF-8");
conn.setDoOutput(true);
OutputStreamWriter osw=new OutputStreamWriter(conn.getOutputStream());
osw.write(data);
osw.flush();
osw.close();
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line,sb="";
while((line=br.readLine())!=null)
{
sb+=line;
}
return sb;
}
catch (Exception e)
{
e.printStackTrace();
return new String(e.getMessage().toString());
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// It will get the response from server
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
}
}
响应代码 200 用于成功的 HTTP 请求。
因此,将 if (response != 200)
替换为 if (response == 200)
。
使用 <uses-permission android:name="android.permission.INTERNET" />
更改您的权限。
你有没有得到像线程 StrictMode 这样的东西??? 尝试在执行异步任务之前调用它。
https://developer.android.com/reference/android/os/StrictMode.ThreadPolicy.Builder.html
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build(); StrictMode.setThreadPolicy(policy);