package com.example.Demo_9;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private Button button;
private String result="";
private Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
final TextView textView = (TextView) findViewById(R.id.text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
send();
Message m = handler.obtainMessage();
handler.sendMessage(m);
}
}).start();
}
});
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (result != null) {
textView.setText(result);
}
super.handleMessage(msg);
}
};
}
public void send() {
String target = "http://192.168.1.161:8080/blog/demo.json";
HttpClient client = new DefaultHttpClient();
HttpPost requet = new HttpPost(target);
HttpResponse response;
try {
response = client.execute(requet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
} else {
result = "connection failed!"; //
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
刚开始写这个,怎么老是得到 result = "connection failed!"; 呢? 手机能够连接到tomcat服务器的demo.json文件的,这没问题的。我哪里逻辑错了吗?我想把json文件内容显示到textview上的....
Every time I see someone using HttpClient, I just want to say this: Google has abandoned HttpClient, and the HttpClient library has been deleted in 6.0. So is there any point in solving your problem? After your problem is solved, how will you solve the version compatibility problem?
Let’s change the HTTP request library first.
The pseudo code is roughly as follows:
It is best to customize a thread pool. ThreadPoolExecutor is very convenient to use.
However, you should use OkHttp or Retrofit for network requests, which is very convenient.
Connection failed! is defined by you, and there is no way to see what information is returned. You'd better debug and look at the return code and information in Response
@Youming is right, and even checked it on purpose: