【问题标题】:I am trying http connection over android我正在尝试通过 android 进行 http 连接
【发布时间】:2014-10-18 11:26:45
【问题描述】:

我是 android 开发的新手,我在测试通过 http 连接发送短信并获取返回字符串时收到此错误消息。下面是http api:

http://server:port/CreditCheck/checkcredits?username=xxxxx&password=xxxx

我收到java.io.ioexception,我不知道如何进一步追踪,这真的让我很头疼。

public class Sender {
    // Username that is to be used for submission
    String username;
    // password that is to be used along with username
    String password;
    // Message content that is to be transmitted
    String message;
    /**
    * What type of the message that is to be sent
    * <ul>
    * <li>0:means plain text</li>
    * <li>1:means flash</li>
    * <li>2:means Unicode (Message content should be in Hex)</li>
    * <li>6:means Unicode Flash (Message content should be in Hex)</li>
    * </ul>
    */
    String type;
    /**
    * Require DLR or not
    * <ul>
    * <li>0:means DLR is not Required</li>
    * <li>1:means DLR is Required</li>
    * </ul>
    */
    String dlr;
    /**
    * Destinations to which message is to be sent For submitting more than one
    * destination at once destinations should be comma separated Like
    * 91999000123,91999000124
    */
    String destination;
    // Sender Id to be used for submitting the message
    String source;
    // To what server you need to connect to for submission
    String server;
    // Port that is to be used like 8080 or 8000
    int port;
    // urlParts is the excessive part of the URL
    //String urlParts;

    public Sender(String server, int port, String username, String password, 
            String message, String dlr, String type, String destination, String source) {

        this.username = username;
        this.password = password;
        this.message = message;
        this.dlr = dlr;
        this.type = type;
        this.destination = destination;
        this.source = source;
        this.server = server;
        this.port = port;

    }


    public String checkBalance() {
        try {

            // Url that will be called to submit the message
            URL sendUrl = new URL("http://" + this.server + ":" + this.port
            + "/CreditCheck/checkcredits");
            HttpURLConnection httpConnection = (HttpURLConnection) sendUrl
            .openConnection();
            // This method sets the method type to POST so that
            // will be send as a POST request
            httpConnection.setRequestMethod("POST");
            // This method is set as true wince we intend to send
            // input to the server
            httpConnection.setDoInput(true);
            // This method implies that we intend to receive data from server.
            httpConnection.setDoOutput(true);
            // Implies do not use cached data
            httpConnection.setUseCaches(false);

            // Data that will be sent over the stream to the server.
            DataOutputStream dataStreamToServer = new DataOutputStream(
            httpConnection.getOutputStream());
            dataStreamToServer.writeBytes("username="
            + URLEncoder.encode(this.username, "UTF-8") + "&password="
            + URLEncoder.encode(this.password, "UTF-8"));

            dataStreamToServer.flush();
            dataStreamToServer.close();
            // Here take the output value of the server.
            BufferedReader dataStreamFromUrl = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String dataFromUrl = "", dataBuffer = "";
            // Writing information from the stream to the buffer
            while ((dataBuffer = dataStreamFromUrl.readLine()) != null) {
                dataFromUrl += dataBuffer;
            }
            /**
            * Now dataFromUrl variable contains the Response received from the
            * server so we can parse the response and process it accordingly.
            */
            dataStreamFromUrl.close();
            //System.out.println("Response: " + dataFromUrl);
            return dataFromUrl;
        } catch (IOException ex) {

            ex.printStackTrace();
            return ex.toString();
        }catch(Exception ex){
            ex.printStackTrace();
            return ex.toString();
        }
    }

    public String submitMessage() {
        try {
            // Url that will be called to submit the message
            URL sendUrl = new URL("http://" + this.server + ":" + this.port + "/bulksms/bulksms");
            HttpURLConnection httpConnection = (HttpURLConnection) sendUrl.openConnection();

            // This method sets the method type to POST so that
            // will be send as a POST request
            httpConnection.setRequestMethod("GET");
            // This method is set as true wince we intend to send
            // input to the server
            httpConnection.setDoInput(true);
            // This method implies that we intend to receive data from server.
            httpConnection.setDoOutput(true);
            // Implies do not use cached data
            httpConnection.setUseCaches(false);

            // Data that will be sent over the stream to the server.
            DataOutputStream dataStreamToServer = new DataOutputStream(httpConnection.getOutputStream());
            dataStreamToServer.writeBytes("username="
            + URLEncoder.encode(this.username, "UTF-8") + "&password="
            + URLEncoder.encode(this.password, "UTF-8") + "&type="
            + URLEncoder.encode(this.type, "UTF-8") + "&dlr="
            + URLEncoder.encode(this.dlr, "UTF-8") + "&destination="
            + URLEncoder.encode(this.destination, "UTF-8") + "&source="
            + URLEncoder.encode(this.source, "UTF-8") + "&message="
            + URLEncoder.encode(this.message, "UTF-8"));

            dataStreamToServer.flush();
            dataStreamToServer.close();

            // Here take the output value of the server.
            BufferedReader dataStreamFromUrl = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String dataFromUrl = "";
            String dataBuffer = "";

            // Writing information from the stream to the buffer
            while ((dataBuffer = dataStreamFromUrl.readLine()) != null) {
                dataFromUrl += dataBuffer;
            }
            /**
            * Now dataFromUrl variable contains the Response received from the
            * server so we can parse the response and process it accordingly.
            */
            dataStreamFromUrl.close();
            //System.out.println("Response: " + dataFromUrl);
            return dataFromUrl;

        } catch (IOException ex) {
            //ex.printStackTrace();
            return ex.toString();
        }catch(Exception ex){
            return ex.toString();
        }
    }

下面是我对 onClicklistener 按钮的调用脚本

public void onClick(View v) {
        Sender s = new Sender("server", port, "username", "password", "test for unicode", "1", "0", "23481111111", "Update");
        switch(v.getId()){
            case R.id.btnSaveSettings:
                Toast.makeText(getActivity(), s.submitMessage().toString(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.btnBalance:
                Toast.makeText(getActivity(), s.checkBalance().toString(), Toast.LENGTH_SHORT).show();

                break;
            default:
                Toast.makeText(getActivity(), "No button Captured", Toast.LENGTH_SHORT).show();

        }
}

请帮我看看我做错了什么!

@Angad 我已经编辑了代码,下面是它的样子和我遇到的错误。

我的调用方式

public String checkBalance() {
    try {
        HttpClient client=new DefaultHttpClient();

        HttpPost request=new HttpPost("http://" + this.server + ":" + this.port + "/CreditCheck/checkcredits");

        BasicNameValuePair username=new BasicNameValuePair("username", this.username);
        BasicNameValuePair password=new BasicNameValuePair("password", this.password);

        List<NameValuePair> list=new ArrayList<NameValuePair>();
        list.add(username);
        list.add(password);

        UrlEncodedFormEntity urlentity=new UrlEncodedFormEntity(list);
        request.setEntity(urlentity);

        HttpResponse response=client.execute(request);

        HttpEntity entity=response.getEntity();
        String tmp=EntityUtils.toString(entity);
        return tmp;

    }catch(Exception ex){
        ex.printStackTrace();
        return ex.toString();
    }
}

我的 Onclick 动作实现方法 checkBalance()

public void onClick(View v) {
    Sender s = new Sender("111.211.211.111", 8080, "user",
            "pass", "test for unicode", "1", "0", "234811111111", "Update");
    // TODO Auto-generated method stub
    switch(v.getId()){
        case R.id.btnSaveSettings:
            //this.savePreferences();
            Toast.makeText(getActivity(), s.submitMessage().toString(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.btnBalance:

            Toast.makeText(getActivity(), s.checkBalance().toString(), Toast.LENGTH_SHORT).show();

            break;
        default:
            Toast.makeText(getActivity(), "No button Captured", Toast.LENGTH_SHORT).show();

    }

我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


</manifest>

异常错误 Android.os.NetworkOnMainThreadException

错误消息 logcat 包括 StackTrace()

10-19 14:22:20.285:E/SoundPool(1273):错误加载 /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285:E/SoundPool(1273):错误加载 /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285:E/SoundPool(1273):错误加载 /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285:E/SoundPool(1273):错误加载 /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.295:E/SoundPool(1273):错误加载 /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.295:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.305:E/SoundPool(1273):错误加载 /system/media/audio/ui/KeypressStandard.ogg 10-19 14:22:20.305:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/KeypressStandard.ogg 10-19 14:22:20.305:E/SoundPool(1273):错误加载 /system/media/audio/ui/KeypressSpacebar.ogg 10-19 14:22:20.315:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/KeypressSpacebar.ogg 10-19 14:22:20.315:E/SoundPool(1273):错误加载 /system/media/audio/ui/KeypressDelete.ogg 10-19 14:22:20.315:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/KeypressDelete.ogg 10-19 14:22:20.325: W/System.err(1854): android.os.NetworkOnMainThreadException 10-19 14:22:20.325:E/SoundPool(1273):错误加载 /system/media/audio/ui/KeypressReturn.ogg 10-19 14:22:20.325:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/KeypressReturn.ogg 10-19 14:22:20.325:E/SoundPool(1273):错误加载 /system/media/audio/ui/KeypressInvalid.ogg 10-19 14:22:20.325:W/AudioService(1273):Soundpool 无法加载文件:/system/media/audio/ui/KeypressInvalid.ogg 10-19 14:22:20.335: W/AudioService(1273): onLoadSoundEffects(), 加载样本时出错 -1 10-19 14:22:20.335: W/System.err(1854): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 10-19 14:22:20.335: W/System.err(1854): 在 libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 10-19 14:22:20.335: W/System.err(1854): 在 libcore.io.IoBridge.connectErrno(IoBridge.java:127) 10-19 14:22:20.335: W/System.err(1854): 在 libcore.io.IoBridge.connect(IoBridge.java:112) 10-19 14:22:20.345: W/System.err(1854): 在 java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 10-19 14:22:20.345: W/System.err(1854): 在 java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 10-19 14:22:20.345: W/System.err(1854): 在 java.net.Socket.connect(Socket.java:843) 10-19 14:22:20.345: W/System.err(1854): 在 org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 10-19 14:22:20.345: W/System.err(1854): 在 org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 10-19 14:22:20.355: W/System.err(1854): 在 org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 10-19 14:22:20.355: W/System.err(1854): 在 org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 10-19 14:22:20.355: W/System.err(1854): 在 org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 10-19 14:22:20.355: W/System.err(1854): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 10-19 14:22:20.365: W/System.err(1854): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-19 14:22:20.365: W/System.err(1854): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 10-19 14:22:20.375: W/System.err(1854): 在 com.example.sleeksmsmobile.Sender.checkBalance(Sender.java:96) 10-19 14:22:20.375: W/System.err(1854): 在 com.example.sleeksmsmobile.SettingsTab.onClick(SettingsTab.java:86) 10-19 14:22:20.375: W/System.err(1854): 在 android.view.View.performClick(View.java:4438) 10-19 14:22:20.385: W/System.err(1854): 在 android.view.View$PerformClick.run(View.java:18422) 10-19 14:22:20.385: W/System.err(1854): 在 android.os.Handler.handleCallback(Handler.java:733) 10-19 14:22:20.385: W/System.err(1854): 在 android.os.Handler.dispatchMessage(Handler.java:95) 10-19 14:22:20.385: W/System.err(1854): 在 android.os.Looper.loop(Looper.java:136) 10-19 14:22:20.395: W/System.err(1854): 在 android.app.ActivityThread.main(ActivityThread.java:5017) 10-19 14:22:20.395: W/System.err(1854): 在 java.lang.reflect.Method.invokeNative(Native Method) 10-19 14:22:20.395: W/System.err(1854): 在 java.lang.reflect.Method.invoke(Method.java:515) 10-19 14:22:20.405: W/System.err(1854): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 10-19 14:22:20.405: W/System.err(1854): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 10-19 14:22:20.415: W/System.err(1854): 在 dalvik.system.NativeStart.main(Native Method) 10-19 14:22:20.925:I/Choreographer(1273):跳过 36 帧!应用程序可能在其主线程上做了太多工作。

【问题讨论】:

  • 你能提供来自 ex.printStackTrace() 的完整错误信息吗?
  • ioexception 在哪一行?还告诉我行语句...'
  • @angad tiwari ioexception 出现在 onclick 操作期间,在 Toast.maketext 操作中调用 submitmessage 和 checkbalance Toast.makeText(getActivity(), s.checkBalance().toString(), Toast.LENGTH_SHORT) 。显示(); Toast.makeText(getActivity(), s.submitMessage().toString(), Toast.LENGTH_SHORT).show();
  • @ArnePoths 我必须从我的 android 设备上进行测试,因为我不知道如何在我的模拟器上上网,所以我如何实现 printStackTrace() 或者我将它转换为字符串以便我可以显示它在 Toast.makeText()
  • stacktrace会出现在logcat输出中,不需要Toast

标签: java android httpurlconnection


【解决方案1】:

在 Android 中,您必须在与用户界面不同的线程上运行网络操作。否则,发送 HTTP 请求的行为会导致接口冻结。

Android documentation

【讨论】:

  • 我的设备没有死机,一切似乎都运行良好,但是在执行 submitMessage 和 checkBalance 时才出现错误消息。谢谢
【解决方案2】:

您的代码在注释和实际编码之间存在矛盾:

        // This method sets the method type to POST so that
        // will be send as a POST request
        httpConnection.setRequestMethod("GET");

然后继续将 setDoInput 和 setDoOutput 都设置为 true:

        // This method is set as true wince we intend to send
        // input to the server
        httpConnection.setDoInput(true);
        // This method implies that we intend to receive data from server.
        httpConnection.setDoOutput(true);

setDoOutput(true) 将请求方法隐式设置为 POST,因为这是您想要发送请求正文时的默认方法。 (见HttpURLConnection sends a POST request even though httpCon.setRequestMethod("GET"); is set)。这可能会导致错误。

如需进一步研究,请指出错误位置(源代码行)。

【讨论】:

  • 非常感谢我在故障排除期间不得不更改请求方法,我将改回 POST 但错误仍然存​​在。错误位置是这个 Toast.makeText(getActivity(), s.submitMessage().toString(), Toast.LENGTH_SHORT).show();或 Toast.makeText(getActivity(), s.checkBalance().toString(), Toast.LENGTH_SHORT).show();
【解决方案3】:

我很高兴通知所有关心我的问题的人,该问题已得到解决。

我的代码运行良好,而 Angad Tiwari 的运行也更简单。

在我能够在我的 avd 上上网后,我可以使用 printStackTrace() 错误报告来查找严格模式策略的原因

解决方法是让我把这段代码放在下面的 mainActivity 类中;

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

感谢大家.....:)

【讨论】:

    【解决方案4】:

    宁可使用httpconnection,我建议你使用httpclient 喜欢

              try
                {
                    HttpClient client=new DefaultHttpClient();
                    HttpPost request=new HttpPost("your url");
    
                    BasicNameValuePair email=new BasicNameValuePair("username", "your username");
                    BasicNameValuePair password=new BasicNameValuePair("password", "your password");
    
                    List<NameValuePair> list=new ArrayList<NameValuePair>();
                    list.add(username);
                    list.add(password);
    
                    UrlEncodedFormEntity urlentity=new UrlEncodedFormEntity(list);
                    request.setEntity(urlentity);
    
                    HttpResponse response=client.execute(request);
    
                    HttpEntity entity=response.getEntity();
                    String tmp=EntityUtils.toString(entity);
                    return tmp;
                }
                catch(Exception e)
                {
                    return e.toString();
                }
    

    用这个试试你的代码...然后告诉我...我肯定会工作...而且它也很简单...所有的网格都与流和所有...希望这会有所帮助...; -)

    【讨论】:

    • 我已经实现了代码,请在我的问题中阅读上面的代码和错误消息,包括 printStackTrace()。请帮帮我!
    • 除此之外。你还可以先检查浏览器上的响应..使用 ADVANCE REST CLIENT chrome 扩展...因此你知道..问题出在哪里。
    • 问题已解决,请仔细阅读我的回答。我很高兴与伙计们:)
    猜你喜欢
    • 2023-03-26
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多