Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我正在尝试通过android进行http连接_Java_Android_Httpurlconnection - Fatal编程技术网

Java 我正在尝试通过android进行http连接

Java 我正在尝试通过android进行http连接,java,android,httpurlconnection,Java,Android,Httpurlconnection,我是android开发的新手,在测试通过http连接发送sms并获取返回字符串时,我收到了此错误消息。以下是http api: http://server:port/CreditCheck/checkcredits?username=xxxxx&password=xxxx 我得到java.io.ioexception,我不知道如何进一步跟踪,这真的让我头疼 public class Sender { // Username that is to be used for subm

我是android开发的新手,在测试通过http连接发送sms并获取返回字符串时,我收到了此错误消息。以下是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();
        }
    }
请帮我解决我做错了什么

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

我的呼叫方法

我的清单文件

异常错误 Android.os.NetworkOnMainThreadException

包含StackTrace的错误消息logcat

10-19 14:22:20.285:E/SoundPool1273:error loading/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.285:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.285:E/SoundPool1273:error loading/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.285:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.285:E/SoundPool1273:error loading/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.285:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.285:E/SoundPool1273:error loading/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.285:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.295:E/SoundPool1273:加载错误/系统/媒体/音频/ui/Effect_Tick.ogg 10-19 14:22:20.295:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/Effect\u Tick.ogg 10-19 14:22:20.305:E/SoundPool1273:加载错误/system/media/audio/ui/KeypressStandard.ogg 10-19 14:22:20.305:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/KeypressStandard.ogg 10-19 14:22:20.305:E/SoundPool1273:error loading/system/media/audio/ui/Keypress Spacebar.ogg 10-19 14:22:20.315:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/KeypressSpacebar.ogg 10-19 14:22:20.315:E/SoundPool1273:加载错误/system/media/audio/ui/KeypressDelete.ogg 10-19 14:22:20.315:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/keypress delete.ogg 10-19 14:22:20.325:W/System.err1854:android.os.NetworkOnMainThreadException 10-19 14:22:20.325:E/SoundPool1273:加载错误/system/media/audio/ui/KeypressReturn.ogg 10-19 14:22:20.325:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/KeypressReturn.ogg 10-19 14:22:20.325:E/SoundPool1273:加载/system/media/audio/ui/KeypressInvalid.ogg时出错 10-19 14:22:20.325:W/AudioService1273:Soundpool无法加载文件:/system/media/audio/ui/keypress invalid.ogg 10-19 14:22:20.335:W/AudioService1273:onLoadSoundEffects,加载样本时出现错误-1 10-19 14:22:20.335:W/System.err1854:at android.os.StrictMode$AndroidBlockGuardPolicy.onNetworkStrictMode.java:1145 10-19 14:22:20.335:W/System.err1854:at libcore.io.BlockGuardOs.connectBlockGuardOs.java:84 10-19 14:22:20.335:W/System.err1854:at libcore.io.IoBridge.connectErrnoIoBridge.java:127 10-19 14:22:20.335:W/System.err1854:at libcore.io.IoBridge.connectIoBridge.java:112 10-19 14:22:20.345:W/System.err1854:at java.net.PlainSocketImpl.connectPlainSocketImpl.java:192 10-19 14:22:20.345:W/System.err1854:at java.net.PlainSocketImpl.connectPlainSocketImpl.java:459 10-19 14:22:20.345:W/System.err1854:at java.net.Socket.connectSocket.java:843 10-19 14:22:20.345:W/System.err1854:org.apache.http.conn.scheme.PlainSocketFactory.connectSocketPlainSocketFactory.java:119 10-19 14:22:20.345:W/System.err1854:at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnectionDefaultClientConnectionOperator.java:144 10-19 14:22:20.355:W/System.err1854:at org.apache.http.impl.conn.AbstractPoolEntry.openAbstractPoolEntry.java:164 10-19 14:22:20.355:W/System.err1854:org.apache.http.impl.conn.AbstractPooledConnAdapter.openAbstractPooledConnAdapter.java:119 10-19 14:22:20.355:W/System.err1854:at org.apache.http.impl.client.DefaultRequestDirector.executeDefaultRequestDirector.java:360 10-19 14:22:20.355:W/System.err1854:at org.apache.http.impl.client.AbstractHttpClient.ExecuteActHttpClient.java:555 10-19 14:22:20.365:W/System.err1854:at org.apache.http.impl.client.AbstractHttpClient.ExecuteActHttpClient.java:487 10-19 14:22:20.365:W/System.err1854:at org.apache.http.impl.client.AbstractHttpClient.ExecuteActHttpClient.java:465 10-19 14:22:20.375:W/System.err1854:at com.example.sleeksmsmobile.Sender.checkBalanceSender.java:96 10-19 14:22:20.375:W/System.err1854:at com.example.sleeksmsmobile.SettingsTab.onClickSettingsTab.java:86 10-19 14:22:20.375:W/System.err1854:at-android.view.view.performClickView.java:4438 10-19 14:22:20.385:W/System.err1854:at-android.view.view$PerformClick.runView.java:18422 10-19 14:22:20.385:W/System.err1854:at android.os.Handler.handleCallbackHandler.java:733 10-19 14:22:20.385:W/System.err1854:at android.os.Handler.dispatchMessageHandler.java:95 10-19 14:22:20.385:W/System.err1854:at android.os.Looper.Looper.java:136 10-19 14:22:20.395:W/System.err1854:at android.app.ActivityThread.mainActivityThread.java:5017 10-19 14:22:20.395:W/System.err1854:at java.lang.reflect.Method.invokenactive方法 10-19 14:22:20.395:W/System.err1854:at java.lang.reflect.Method.invokeMethod.java:515 10-19 14:22:20.405:W/System.err1854:com.android.internal.os.ZygoteInit$MethodAndArgsCaller.runZygoteInit.java:779 10-19 14:22:20.405:W/System.err1854:at com.android.internal.os.ZygoteInit.mainZygoteInit.java:595 10-19 14:22:20.415:W/System.err1854:at dalvik.System.NativeStart.main本地方法
10-1914:22:20.925:I/编舞1273:跳过36帧!应用程序可能在其主线程上做了太多的工作。

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


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

        // 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);
setDoOutputtrue隐式地将请求方法设置为POST,因为无论何时您想要发送请求正文,这都是默认方法。看见这可能会导致错误


为了进一步研究,请指出错误位置源行。

我建议您使用httpconnection 像


用这个试试你的代码…告诉我…我一定会工作的…而且它也很简单…在那里它与流和所有。。希望这将有助于-

我很高兴地通知每一位关心我的问题的人,我的问题已经解决了

我的代码运行得很好,Angad Tiwari的代码运行得更简单

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

修复方法是我将下面的代码放在mainActivity类中

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

非常感谢大家……:

您能在哪一行提供ex.printStackTrace?ioexception的完整错误消息吗?还要告诉我行语句…“@angad tiwari ioexception出现在onclick操作期间,在调用submitmessage和checkbalance Toast.makeTextgetActivity、s.checkbalance.toString、Toast.LENGTH_SHORT.show的Toast.maketext操作中;Toast.makeTextgetActivity、s.submitMessage.toString、Toast.LENGTH\u SHORT.show@Arnepoth我必须从我的android设备上进行测试,因为我不知道如何在我的模拟器上获取互联网,因此我如何实现printStackTrace,或者我将其转换为字符串,以便在Toast上显示它。MakeText stacktrace将出现在logcat输出中,不需要Toastmy设备不会冻结,一切似乎都正常工作,但执行submitMessage和checkBalance时会出现错误消息。非常感谢在故障排除期间我不得不更改请求方法,我将更改回POST,但错误仍然存在。错误位置是Toast.makeTextgetActivity、s.submitMessage.toString、Toast.LENGTH\u SHORT.show;或Toast.makeTextgetActivity、s.checkBalance.toString、Toast.LENGTH\u SHORT.show;我已经实现了代码,请在我的问题中阅读上面的代码和错误消息,包括printStackTrace。请帮帮我!除此之外。你也可以先检查浏览器上的响应。使用AdvanceREST客户端chrome扩展…因此我们知道。问题在哪里。问题已解决。请通读我的答案。我很高兴和男人们在一起:
<?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>
        // 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);
          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();
            }
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);