可以发送信息,但无法接受数据
package com.example.myroom.sendmessage;
import android.app.Activity;
import android.content.Context;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends Activity {
private Button send;
private EditText input;
private TextView output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input=(EditText)this.findViewById(R.id.input);
output=(TextView)this.findViewById(R.id.output);
send=(Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String Output=input.getText().toString().trim();
new Thread(new Runnable() {
@Override
public void run() {
String path="http://192.168.11.254:8080";
try {
URL url=new URL(path);
//打开http连接
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
//conn.setRequestMethod("GET");
conn.setConnectTimeout(1000*30);//连接超时时间
conn.setReadTimeout(1000*30);//读取数据的超时时间
conn.setUseCaches(false);
conn.setRequestProperty("content-type","application/x-www-from-urlencoded");
//对服务器端读取或写入数据
DataOutputStream out=new DataOutputStream(conn.getOutputStream());
out.writeBytes(Output);
out.flush();
out.close();
//获取响应数据
InputStreamReader in=new InputStreamReader(conn.getInputStream());
//BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
BufferedReader br=new BufferedReader(in);
String readLine;
String line="";
while((readLine=br.readLine())!=null){
line+=readLine;
}
in.close();
final String finalLine = line;
runOnUiThread(new Runnable() {
@Override
public void run() {
output.setText("内容:"+ finalLine);
Toast.makeText(MainActivity.this,"try!!!",Toast.LENGTH_SHORT).show();
}
});
//System.out.println("result"+result);
conn.disconnect();//关闭连接
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
求助下。。。