java 写socket_java写socket请求

POST请求

public String XHttp(String SendData) {

String ret = null;

Socket mSocket = null;

OutputStream os = null;

InputStream ins = null;

try {

String host = getHost(url);

mSocket = new Socket(host, port);

os = mSocket.getOutputStream();

ins = mSocket.getInputStream();

StringBuffer sb = new StringBuffer();

sb.append("POST ").append(postUrl).append(" HTTP/1.1")

.append("\r\n");

sb.append(

"Accept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, */*")

.append("\r\n");

sb.append("Accept-Language: en-GB,en-US").append("\r\n");

sb.append("Content-Type: application/x-www-form-urlencoded")

.append("\r\n");

sb.append(

"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30618)")

.append("\r\n");

sb.append("Host: ").append(url).append(":").append(port)

.append("\r\n");

sb.append("Content-Length: ").append(SendData.length())

.append("\r\n");

sb.append("Connection: Keep-Alive").append("\r\n");

sb.append("Cache-Control: no-cache").append("\r\n\r\n");

sb.append(SendData);

String Searchname_send = new String(sb.toString().getBytes(), "utf-8");

os.write(Searchname_send.getBytes());

os.flush();

String line = null;

int contentLength = 0;// 服务器发送回来的消息长度

// 读取所有服务器发送过来的请求参数头部信息

do {

line = readLine(ins, 0);

// 如果有Content-Length消息头时取出

if (line.startsWith("Content-Length")) {

contentLength = Integer.parseInt(line.split(":")[1].trim());

}

// 打印请求部信息

// System.out.print(line);

//Log.i(TAG, "line is " + line);

// 如果遇到了一个单独的回车换行,则表示请求头结束

} while (!line.equals("\r\n"));

ret = readLine(ins, contentLength);

// --输消息的体

//Log.i(TAG, "ret is " + ret);

// System.out.print(readLine(ins, contentLength));

// sb = new StringBuffer();

// BufferedReader br = new BufferedReader(new

// InputStreamReader(ins));

// String str = null;

// while ((str = br.readLine()) != null) {

// sb.append(str);

// System.out.println(str);

// }

// br.close();

// ret = sb.toString();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

finally {

if (null != mSocket) {

try {

mSocket.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != os) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != ins) {

try {

ins.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return ret;

}GET请求

public String XHttp(String SendData) {

//String ret = sendmsg("192.168.0.100",SendData);

String ret = null;

// String SendData =

// "<?xml version=\"1.0\" encoding=\"UTF-8\"?>loginss123";

Socket mSocket = null;

OutputStream os = null;

InputStream ins = null;

try {

String host = getHost(url);

//System.out.println(host);

//System.out.println(port);

mSocket = new Socket(host, port);

os = mSocket.getOutputStream();

ins = mSocket.getInputStream();

StringBuffer sb = new StringBuffer();

sb.append("GET ").append(postUrl).append(" HTTP/1.1")

.append("\r\n");

sb.append("Host").append(": ").append(host).append(":")

.append(port).append("\r\n");

sb.append("Connection").append(": ").append("Close").append("\r\n");

sb.append("Accept").append(": ").append("*/*").append("\r\n");

sb.append("\r\n");// end

sb.append("Content-Length: ").append(SendData.length())

.append("\r\n");

sb.append("Connection: Keep-Alive").append("\r\n");

sb.append("Cache-Control: no-cache").append("\r\n\r\n");

sb.append(SendData);

//System.out.println("sb is " + sb);

String Searchname_send = new String(sb.toString().getBytes(), "utf-8");

//byte[] testbyte = Searchname_send.getBytes();

//System.out.println("testbyte.length is "

//+ testbyte.length);

//for (int i = 0; i < testbyte.length; i++) {

//String hex = Integer

//.toHexString(testbyte[i] & 0xFF);

//if (hex.length() == 1) {

//hex = '0' + hex;

//}

//System.out.print(hex.toUpperCase() + " ");

//}

//os.write(sb.toString().getBytes());

os.write(Searchname_send.getBytes());

os.flush();

String line = null;

int contentLength = 0;// 服务器发送回来的消息长度

// 读取所有服务器发送过来的请求参数头部信息

do {

line = readLine(ins, 0);

// 如果有Content-Length消息头时取出

if (line.startsWith("Content-Length")) {

contentLength = Integer.parseInt(line.split(":")[1].trim());

}

// 打印请求部信息

// System.out.print(line);

//Log.i(TAG, "line is " + line);

// 如果遇到了一个单独的回车换行,则表示请求头结束

} while (!line.equals("\r\n"));

ret = readLine(ins, contentLength);

// --输消息的体

//Log.i(TAG, "ret is " + ret);

// System.out.print(readLine(ins, contentLength));

// sb = new StringBuffer();

// BufferedReader br = new BufferedReader(new

// InputStreamReader(ins));

// String str = null;

// while ((str = br.readLine()) != null) {

// sb.append(str);

// System.out.println(str);

// }

// br.close();

// ret = sb.toString();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

finally {

if (null != mSocket) {

try {

mSocket.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != os) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != ins) {

try {

ins.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return ret;

}

public static String getHost(String url) {

Pattern p = Pattern.compile("(http://|https://)?([^/]*)",

Pattern.CASE_INSENSITIVE);

Matcher m = p.matcher(url);

return m.find() ? m.group(2) : url;

}

private static String readLine(InputStream is, int contentLe)

throws IOException {

ArrayList lineByteList = new ArrayList();

byte readByte;

int total = 0;

if (contentLe != 0) {

do {

readByte = (byte) is.read();

lineByteList.add(Byte.valueOf(readByte));

total++;

} while (total < contentLe);// 消息体读还未读完

} else {

do {

readByte = (byte) is.read();

lineByteList.add(Byte.valueOf(readByte));

} while (readByte != 10);

}

byte[] tmpByteArr = new byte[lineByteList.size()];

for (int i = 0; i < lineByteList.size(); i++) {

tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue();

}

lineByteList.clear();

return new String(tmpByteArr, encoding);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值