android用POST方式请求网络,多的不说了 直接上代码
//请求代码
public static String Post(String string,String get,Context context)//string POST参数,get 请求的URL地址,context 联系上下文
{
try {
String urldizhi=get; //请求地址
URL url=new URL(urldizhi);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(50000);//超时时间
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// conn.setRequestProperty("User-Agent", Other.getUserAgent(context));
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(string);
out.flush();
out.close();
InputStream inputStream=conn.getInputStream();
byte[] data=StreamTool.read(inputStream);
html = new String(data, "utf-8");
} catch (Exception e) {
System.out.println("-----"+e);
String string2="{\"success\":-1}";
return string2;
}
return html;
}
还有一个类我也贴出来
package com.sutong.feihua.http;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamTool {
<span style="white-space:pre"> </span>/**
<span style="white-space:pre"> </span> *
<span style="white-space:pre"> </span> * @param inStream
<span style="white-space:pre"> </span> * @return
<span style="white-space:pre"> </span> * @throws Exception
<span style="white-space:pre"> </span> */
<span style="white-space:pre"> </span>public static byte[] read(InputStream inStream) throws Exception{
<span style="white-space:pre"> </span>ByteArrayOutputStream outStream = new ByteArrayOutputStream();
<span style="white-space:pre"> </span>byte[] buffer = new byte[1024];
<span style="white-space:pre"> </span>int len = 0;
<span style="white-space:pre"> </span>while( (len = inStream.read(buffer)) != -1){
<span style="white-space:pre"> </span>outStream.write(buffer, 0, len);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>inStream.close();
<span style="white-space:pre"> </span>return outStream.toByteArray();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public FileInputStream output(String fileString)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>File file = new File(fileString);
<span style="white-space:pre"> </span>FileInputStream fileInputStream = null;
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>fileInputStream = new FileInputStream(file);
<span style="white-space:pre"> </span>} catch (FileNotFoundException e) {
<span style="white-space:pre"> </span>// TODO Auto-generated catch block
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return fileInputStream;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
}