나는 HttpURLConnection을 사용하여 원격 URL 콘텐츠를 얻으려고하지만 빈 결과를 얻고있다. 요청을 얻는 것을 볼 수있는 charle 프록시를보고 있지만 안드로이드는 응답을 저장할 수 없다! 이 코드? 사전에 감사드립니다.HttpURLConnection을 사용하여 Android URL 콘텐츠를 가져 오는 방법은 무엇입니까?
public String sendGetRequest() {
try {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://www.bbc.com").openConnection();
myURLConnection.setReadTimeout(60000);
myURLConnection.setConnectTimeout(60000);
myURLConnection.setRequestMethod("GET");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.setRequestProperty("Content-Type", "text/plain");
myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;)");
myURLConnection.setRequestProperty("Connection", "Keep-Alive");
myURLConnection.addRequestProperty("Content-length", "");
OutputStream os = myURLConnection.getOutputStream();
os.close();
myURLConnection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
return sb.toString();
} catch (Exception e) {
}
return null;
}
난 버튼의 onclick로부터 상기 함수를 호출
public Button but1;
//creating public method
public void init() {
but1 = (Button) findViewById(R.id.but1);
//wire our button
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String finalResult = sendGetRequest();
mWebView.loadUrl("javascript:displayIt(" + finalResult+ ")");
}
});
} 가
편집 (사용 백그라운드 프로세스)
:public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
}
setDoOutput은 POST 요청을위한 것이며, 연결을 열어도 bebfore를 얻고 있습니다. 기대되는 결과를 알지 못합니다. 또한 URL이 자바 스크립트 인 이유는 무엇입니까? –