Java下通过发送http post请求的代码
2018-07-20 来源:open-open
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import org.apache.http.protocol.HTTP; import com.everyone.android.callback.ParseCallback; import com.everyone.android.callback.ResultCallback; /** * 功能描述:通过HTTP协议发送POST请求 * @author android_ls * */ public class AsyncHttpPost extends AsyncBaseRequest { /** * */ private static final long serialVersionUID = 3L; public AsyncHttpPost(String url, Map<String, String> parameter, ParseCallback handler, ResultCallback requestCallback) { super(url, parameter, handler, requestCallback); } @Override protected InputStream getRequestResult() throws IOException { StringBuilder sb = new StringBuilder(); if(parameter!=null && !parameter.isEmpty()){ for(Map.Entry<String, String> entry : parameter.entrySet()){ sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), HTTP.UTF_8)).append('&'); } sb.deleteCharAt(sb.length()-1); } // 得到实体的二进制数据 byte[] entitydata = sb.toString().getBytes(); URL url = new URL(requestUrl); mHttpURLConn = (HttpURLConnection)url.openConnection(); mHttpURLConn.setRequestMethod("POST"); mHttpURLConn.setConnectTimeout(5 * 1000); // 如果通过post提交数据,必须设置允许对外输出数据 mHttpURLConn.setDoOutput(true); mHttpURLConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); mHttpURLConn.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); OutputStream outStream = mHttpURLConn.getOutputStream(); outStream.write(entitydata); outStream.flush(); outStream.close(); if(mHttpURLConn.getResponseCode()== HttpURLConnection.HTTP_OK){ return mHttpURLConn.getInputStream(); } return null; } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
下一篇:java计算数学表达式
最新资讯
热门推荐