当前位置: 首页 > 知识库问答 >
问题:

我正在尝试android上的http连接

松兴邦
2023-03-14

我是android开发的新手,在测试通过http连接发送短信并获得返回字符串时,我遇到了这个错误消息。下面是http API:

http://server:port/CreditCheck/checkcredits?username=xxxxx&password=xxxx
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();
        }
    }
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();

        }
}
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();
    }
}
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>

共有1个答案

程磊
2023-03-14

相反,使用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();
            }

试着用这个代码...告诉我...我一定会工作的...它也很简单...那里有所有与流的网状连接和所有..希望这能有所帮助...;-)

 类似资料:
  • 我正在尝试将本地Spring Boot应用程序连接到我的Heroku Postgres数据库。当我使用Heroku上可用的creds尝试此操作时,我得到以下错误 错误:SEVERITY_LOCALIZED=FATAL,SEVERITY_NON_LOCALIZED=FATAL, CODE=28000, MESSAGE=没有主机"myhost",用户"myuser",数据库"mydb"的pg_hba.

  • 我目前正在尝试与我的android应用程序和我的openfire服务器(在ubuntu上工作)握手。但我不能。我没有失败之类的。只是什么都没发生。这感觉很糟糕。

  • 问题内容: 我正在尝试遵循Zed Shaw的《困难方法学习Python》指南。我需要在Powershell中使用python。我在中安装了Python 2.7.3 。每当我在Powershell中键入python时,都会出现一个错误,指出“ python”一词无法识别为cmdlet,函数,脚本文件或可操作程序的名称。我也输入了以下内容: 提供了建议的解决方案,但是在Powershell中输入pyt

  • 第5.12季度 我正在尝试获取macOS上的卷ID,并使用以下函数: 由于macOS的限制,我不得不使用diskutil。然而,QProcess,读取对象没有任何内容。 终端上的命令:diskutil info$(df-h/|ail-1|Cut-d''-f 1)返回大量信息,例如: ... 智能状态: 已验证 卷 UUID: 954BACF1-EBC5-4D14-86FB-0912CF7F839C

  • 对于我的项目,我需要在有Android Jelly bean的设备中实现HDR功能。从代码中我看到,当选择HDR(高动态范围)时,应用程序正在向HAL层发送SCENE\u MODE\u HDR。我是相机HAL层的开发者。当我得到scene mode=scene\u mode\u HDR时,我应该做什么。我是否需要请求驱动程序提供3幅具有不同曝光补偿值的图像,并且应用程序将负责拼接图像以生成HDR图

  • 我用我的力量运行这个命令行 并返回此错误,在此处输入图像描述