我的要求:
String path = "https://...";
HttpURLConnection urlConnection = null;
try{
URL url = new URL(path);
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection = Tools.setHeader(urlConnection);
urlConnection.setDoInput(true);
LOG.debug("Start input stream");
InputStream inputStream = urlConnection.getInputStream();
LOG.debug("Input stream exist "+inputStream.toString());
String response = Tools.streamToString(inputStream);
inputStream.close();
JSONObject jsonResponse = new JSONObject(response);
我没有收到任何错误消息。使用代理服务器,我看到我的请求已发送并收到响应。但是在程序中urlConnection.getInputStream()
方法什么也得不到。该计划不会更进一步。我没有看到第二个日志。
我试图设置超时,但这没有用。响应很快(1-2秒)。
答案 0 :(得分:1)
Heyy我在手机或平板电脑上使用以下代码运行。我正在为您提供我的代码,看看它。
代码:
public class URLConnectionCheck extends Activity {
TextView resultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urlconnection_check);
resultText = (TextView)findViewById(R.id.resultTextView);
new AsynchTaskTest().execute();
}
private class AsynchTaskTest extends AsyncTask<Void,Void,String>
{
@Override
protected String doInBackground(Void... params) {
String path = "http://echo.jsontest.com/key/value/one/two";
HttpURLConnection urlConnection = null;
BufferedReader reader=null;
try{
URL url = new URL(path);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) !=null) {
buffer.append(line+"\n");
}
return buffer.toString();
}
catch (Exception e)
{
e.printStackTrace();
return "exception";
}
}
@Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
resultText.setText(aVoid);
}
}
}
结果在我的屏幕上显示为::