android POST请求

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/json");  
//      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 {  
    /** 
    *  
    * @param inStream 
    * @return 
    * @throws Exception 
    */  
    public static byte[] read(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len = inStream.read(buffer)) != -1){  
            outStream.write(buffer, 0, len);  
        }  
        inStream.close();  
        return outStream.toByteArray();  
    }  
    public FileInputStream output(String fileString)  {  
        File file = new File(fileString);  
        FileInputStream fileInputStream = null;  
        try {  
            fileInputStream = new FileInputStream(file);  
        } catch (FileNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
    }  
return fileInputStream;  
}  
  
  
}  

你可能感兴趣的:(android POST请求)