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"; //String path="http://192.168.111.93"; try { URL url=new URL(path); //打开http连接 HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(false); conn.setRequestMethod("POST"); // conn.setRequestMethod("GET"); conn.setConnectTimeout(1000*30);//连接超时时间 conn.setReadTimeout(1000*30);//读取数据的超时时间 conn.setUseCaches(false);// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接// conn.setRequestProperty("Charset", "UTF-8");// conn.setRequestProperty("Content-type", "application/x-java-serialized-object"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.connect(); //对服务器端读取或写入数据 //DataOutputStream out=new DataOutputStream(conn.getOutputStream()); OutputStream out=conn.getOutputStream(); out.write(Output.getBytes()); //out.writeBytes(Output); out.flush(); out.close(); //获取响应数据 int code=conn.getResponseCode(); String sCurrentLine=""; String sTotalString=""; if(code==200){ InputStream os=conn.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(os)); while((sCurrentLine=reader.readLine())!=null){ if(sCurrentLine.length()>0){ sTotalString=sTotalString+sCurrentLine.trim(); } } final String finalLine = sTotalString; runOnUiThread(new Runnable() { @Override public void run() { output.setText("内容:"+ finalLine); Toast.makeText(MainActivity.this,"try!!!",Toast.LENGTH_SHORT).show(); } }); }else{ Toast.makeText(MainActivity.this,"fail!",Toast.LENGTH_LONG).show(); } //InputStreamReader in=new InputStreamReader(conn.getInputStream());// BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));// //BufferedReader br=new BufferedReader(in);// String readLine;// StringBuffer strbuffer=new StringBuffer();// String line=null;// while((readLine=br.readLine())!=null){//// line+=readLine;// strbuffer.append(readLine);// strbuffer.append("\n");// }//// line=strbuffer.toString();// br.close(); //System.out.println("result"+result); conn.disconnect();//关闭连接 } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }); }}真的无法找到原因了,求助求助
添加回答
举报
0/150
提交
取消