用httpurlconnection时当要outputstream时中断连接,这是为什么
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(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();
//对服务器端读取或写入数据
OutputStream outStrm=conn.getOutputStream();
//获取响应数据
ObjectOutputStream outputStream=new ObjectOutputStream(outStrm);
outputStream.writeObject(Output);
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();
}
//System.out.println("result"+result);
conn.disconnect();//关闭连接
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}
...全文
相关推荐
HttpURLConnection用法详解
安全性使用HTTPS时,HttpURLConnection会自动处理SSL/TLS加密,但也可以自定义SSLContext和HostnameVerifier以进行更精细的控制。### 12.
java 使用HttpURLConnection发送数据简单实例
三、使用HttpURLConnection发送POST数据使用HttpURLConnection发送POST数据需要使用 OutputStream 流的形式发送。
android HttpURLConnection上传图片demo
实例,并设置其连接属性。
一文读懂JAVA中HttpURLConnection的用法
例如:OutputStream outStrm = httpUrlConnection.getOutputStream();ObjectOutputStream objOutputStrm = new
远程连接服务器HttpURLConnection
例如:```javaURL url = new URL("http://example.com");HttpURLConnection connection = (HttpURLConnection)


