网址未发送回响应...也没有异常

时间:2018-06-28 16:49:50

标签: java android api

我已经尝试了所有的解决方案,但是没有得到什么?

这是我的Android清单文件。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.fuel_trade">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是我的构建gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.user.fuel_trade"
        minSdkVersion 17
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

这是HTTP处理程序。 这是建立连接的类 在这里,我尝试打印返回的连接代码,但该语句未执行... 我可以说openConnection下面的LOG语句没有执行

    package com.example.user.fuel_trade;

    import android.net.ConnectivityManager;
    import android.util.Log;

     import java.io.BufferedInputStream;
     import java.io.BufferedReader;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.net.HttpURLConnection;
     import java.net.MalformedURLException;
     import java.net.URL;

/**
 * Created by User on 6/24/2018.
 */

    public class HttpHandler {
    private static final String TAG=HttpHandler.class.getSimpleName();

    public HttpHandler(){}



    public String makeServiceCall(String reqUrl)
    {
        HttpURLConnection conn=null;
        String response=null;
        try
        {
            int y;
            Log.e(TAG,"I NA");
            Log.e(TAG,"hey"+reqUrl);
            URL url=new URL(reqUrl);
            conn=(HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            y=conn.getResponseCode();
            Log.e(HttpHandler.class.getSimpleName(),"code:"+y);

            InputStream in=new BufferedInputStream(conn.getInputStream());
            response=convertStreamToString(in);
        }
        catch(MalformedURLException e)
        {
            Log.e(HttpHandler.class.getSimpleName(),"Malformed");
        }
        catch (IOException e)
        {
            Log.e(HttpHandler.class.getSimpleName(),"io");
        }
        catch (Exception e)
        {

        }
        finally {
            conn.disconnect();
        }
        return response;
    }

    private String convertStreamToString(InputStream in) {
        BufferedReader reader=new BufferedReader(new InputStreamReader(in));
        Log.e(TAG,"reached  here");
        if(reader==null)
            Log.e(HttpHandler.class.getSimpleName(),"no data");
        StringBuilder sb=new StringBuilder();

        String line;
        try
        {
            while((line=reader.readLine())!=null)
            {
                Log.e(TAG,"line"+line);
                sb.append(line).append('\n');
            }
            Log.e(TAG,"no");
        }
        catch (IOException e)
        {
            Log.e(TAG,"IOException");
        }
        finally {
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                Log.e(TAG,"IOException");
            }
        }
      return sb.toString();
    }

}

在这里,我主要活动是尝试打印从url返回但为空的响应

    package com.example.user.fuel_trade;

     import android.support.v7.app.AppCompatActivity;
     import android.os.Bundle;
     import android.util.Log;
     import android.widget.TextView;

     import org.json.JSONException;
     import org.json.JSONObject;

     public class MainActivity extends AppCompatActivity {

    String t;
    TextView x;
    //private static String url="http://still-tundra-35330.herokuapp.com/main/jaipur/petrol/price";
    private static String url= "http://api.androidhive.info/contacts/";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        x=(TextView)findViewById(R.id.display);

        HttpHandler sh=new HttpHandler();
        String jsonStr=sh.makeServiceCall(url);
        Log.e(MainActivity.class.getSimpleName(),"Response from url "+jsonStr);
        if(jsonStr!=null)
        {
            try{
                JSONObject jsonObj=new JSONObject(jsonStr);
                t=jsonObj.getString("price");
                x.setText(t);

            } catch (JSONException e) {
                e.printStackTrace();
                Log.e(MainActivity.class.getSimpleName(),"jsonexception");
            }
        }

    }
}

这是我的LOgcat

    W/System: ClassLoader referenced unknown path: /data/app/com.example.user.fuel_trade-1/lib/arm
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
E/HttpHandler: I NA
E/HttpHandler: heyhttp://api.androidhive.info/contacts/
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/MainActivity: Response from url null
I/Adreno: QUALCOMM build                   : 7d18700, I8ee426a9a2
          Build Date                       : 10/07/16
          OpenGL ES Shader Compiler Version: XE031.09.00.03
          Local Branch                     : mybranch22308589
          Remote Branch                    : quic/LA.BR.1.3.6_rb1.6
          Remote Branch                    : NONE
          Reconstruct Branch               : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1

1 个答案:

答案 0 :(得分:0)

您无法在主线程上进行网络调用,Android会抛出NetworkOnMainThreadException,您必须使用某种形式的线程,可能是AsyncTask 。最好使用Retrofit之类的网络库,那样的话,该库将负责线程处理