我想通过接收来自此服务器的数据来检查与服务器的连接,这是我的代码:
package com.example.sanzharaubakir.fin;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.util.EntityUtils;
/**
* Created by sanzharaubakir on 26.07.16.
*/
public class auth extends Activity {
EditText login;
EditText pswd;
Button ok;
MyTask task;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authorization);
ok = (Button) findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//task = new MyTask();
//task.execute();
new MyTask().doInBackground();
}
});
}
public class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
sendData();
return null;
}
/* @Override
protected void onPreExecute() {
}
protected void onPostExecute(Void result) {
}*/
}
public void sendData()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://144.76.29.144:8001/documents/api/login");
try {
String log = login.getText().toString();
String psw = pswd.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", log));
nameValuePairs.add(new BasicNameValuePair("password", psw));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode();
String tk = EntityUtils.toString(response.getEntity());
if (responseCode == 200)
{
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor e = sPref.edit();
e.putString("token", tk);
e.apply();
Intent intent = getIntent();
String info = intent.getStringExtra("d");
try {
HttpClient client = new DefaultHttpClient();
HttpPost Post = new HttpPost("http://144.76.29.144:8001");
List<NameValuePair> ValuePairs = new ArrayList<NameValuePair>(2);
ValuePairs.add(new BasicNameValuePair("data", info));
ValuePairs.add(new BasicNameValuePair("token", tk));
Post.setEntity(new UrlEncodedFormEntity(ValuePairs,"UTF-8"));
HttpResponse httpResponse = client.execute(Post);
HttpEntity httpEntity = httpResponse.getEntity();
info = EntityUtils.toString(httpEntity,"UTF-8");
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
else {
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
和XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/login"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pswd"
/>
</LinearLayout>
<Button
android:id="@+id/ok"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Log in"
/>
</LinearLayout>
当我尝试点击按钮时,应用程序不幸停止,是否有人知道它为什么会发生? 以下是Log所说的:
FATAL EXCEPTION: main
Process: com.example.sanzharaubakir.fin, PID: 2620
java.lang.NullPointerException
at com.example.sanzharaubakir.fin.auth.sendData(auth.java:76)
at com.example.sanzharaubakir.fin.auth$MyTask.doInBackground(auth.java:60)
at com.example.sanzharaubakir.fin.auth$1.onClick(auth.java:47)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
您正在主线程上进行网络操作。尝试在单独的线程中进行。使用Asynctask。
答案 1 :(得分:0)
使用异步任务进行呼叫网络服务。
答案 2 :(得分:0)
请记住:建议所有耗时的操作(如网络操作和读取数据库)在后台线程中运行,而不是在UI线程中运行。因为它们可能会导致ANR异常。您可以使用AsyncTask或仅使用新的子线程来生成http请求并在主线程(UI线程)中显示该接口。顺便说一句,如果你在Android 2.2之上运行,我建议使用HttpUrlConnection而不是HttpClient。
编辑:使用AsyncTask。
您无法直接调用doInBackground方法,您可以尝试以下代码供您参考。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
...
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyTask().execute(); //you can't invoke the doInBackground method directly
}
});
}
public class MyTask extends AsyncTask<Void, Void, Void> {
/**
* Runs on the UI thread before doInBackground, does preloading works generally speaking
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Runs on the background thread, does time-consuming operations
*/
@Override
protected Void doInBackground(Void... params) {
// when you finish loading, you can call publishProgress to publish updates on the UI thread
return null;
}
/**
* Runs on the UI thread after publishProgress is invoked.
*/
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// you can update the loading progress here
}
/**
* Runs on the UI thread after doInBackground
* This method won't be invoked if the task was cancelled
*/
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}