Android:发送/接收数据

时间:2017-04-11 06:05:20

标签: java android httpclient

package demo.chv.bhudev.chvlogin;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {
TextView content;
EditText login, pass;
String Login, Pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    login      =    (EditText)findViewById(R.id.txt_box_usr);
    pass       =   (EditText)findViewById(R.id.txt_box_pwd);
    content    =   (TextView)findViewById( R.id.txt_content);

    Button save = (Button)findViewById(R.id.btn_login);
    save.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View v)
        {
            try{
                // CALL GetText method to make post method call
                GetText();
            }
            catch(Exception ex)
            {
                content.setText(ex.getMessage());
            }
        }
    });
}

private void GetText() throws UnsupportedEncodingException{
    Login = login.getText().toString();
    Pass = pass.getText().toString();

    Toast.makeText(this,"Started",Toast.LENGTH_LONG).show();
    String data = URLEncoder.encode("username", "UTF-8")
            + "=" + URLEncoder.encode(Login, "UTF-8");

    data += "&" + URLEncoder.encode("password", "UTF-8") + "="
            + URLEncoder.encode(Pass, "UTF-8");

    String text = "";
    try{
        URL url = new URL("mylink");
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        StringBuilder  sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((text = reader.readLine()) != null){
            sb.append(text);
            break;
        }
        content.setText(sb);
    }catch(Exception r)    {    Toast.makeText(this,r.getMessage().toString(),Toast.LENGTH_LONG).show();
    }
}
}

对于上面的代码,我得到异常“尝试在空对象引用上调用虚方法'java.lang.String java.lang.toString()'”。

我在网上尝试/搜索了很多东西,却找不到解决方案。

3 个答案:

答案 0 :(得分:0)

您的登录或传递对象(我认为是edittext视图)在运行此方法之前尚未初始化。这会在空对象引用"

上给出错误"

答案 1 :(得分:0)

更改以下代码:

Toast.makeText(this,r.getMessage().toString(),Toast.LENGTH_LONG).show();

Toast.makeText(this,r.getMessage(),Toast.LENGTH_LONG).show();

以下是Oracle文档中getMessage函数的描述:

<强>的getMessage

public String getMessage()

Returns the detail message string of this throwable.
Returns:the detail message string of this Throwable instance (which may be null).

因此,您可能会变为空

另外,请更改以下代码:

 Login = login.getText().toString();
Pass = pass.getText().toString();

为:

if(login.getText()!=null)
    Login = login.getText().toString();
if(pass.getText()!=null)
        Pass = pass.getText().toString();

答案 2 :(得分:0)

你需要设置哪个请求方法键入你的调用,如POST或GET调用,所以试试这个

 urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Authorization", "Basic " + base64Encoded);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
    out.print(_param);
    out.close();

    int statusCode = urlConnection.getResponseCode();

    if (statusCode == 200) {
        inputStream = new BufferedInputStream(urlConnection.getInputStream());

        try {
            sb = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(
                    _instream));
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                sb.append(line);
            }

            _instream.close();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        //  sb.toString() use where you want
    }